Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/183.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android在listview中设置单个项目的背景色_Android_Listview_Background - Fatal编程技术网

Android在listview中设置单个项目的背景色

Android在listview中设置单个项目的背景色,android,listview,background,Android,Listview,Background,我需要在列表视图中更改所选项目的颜色,我知道如何在单击方法中进行更改,但问题是,我想设置它,然后加载新活动。在该活动中,我正在创建listview,然后我想从该列表中更改一个项目的背景颜色 我试过了 this.slideMenuList = (ListView) findViewById(R.id.listSlideMenu); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>

我需要在列表视图中更改所选项目的颜色,我知道如何在单击方法中进行更改,但问题是,我想设置它,然后加载新活动。在该活动中,我正在创建listview,然后我想从该列表中更改一个项目的背景颜色

我试过了

this.slideMenuList = (ListView) findViewById(R.id.listSlideMenu);
    ArrayAdapter<String> adapter2 =
            new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.menuListResut);
    this.slideMenuList.setAdapter(adapter2);

    this.slideMenuList.getChildAt(0).setBackgroundColor(R.color.red);

但是我得到了空指针

您需要一个自定义适配器;您可能会得到一个NPE,因为视图在需要时才被渲染,而您不能像现在这样可靠地进行渲染。编写自己的适配器类,并在视图膨胀后设置背景色,如下所示:

public class MyAdapter extends BaseAdapter {
  @Override
  public View getView(int i, View convertView, ViewGroup viewGroup) {
    convertView = mInflater.inflate(your layout); // Pseudo-code!
    if (i == 0) {
      convertView.setBackgroundColor(R.color.red);
    }
  }
}

您应该制作一个自定义适配器,然后将位置号传递给构造函数。请检查此链接