简体   繁体   中英

Change background of first item in ListView to red

I have a listView called listv and I'm populating the listView with an array. I want the background of the first item in my listView to be colored red. I can populate the list however I can't get the backgrounds first item in the list to turn red.

This is what I tried. My code is as fallows

My Class

private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
private EditText txtInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_deadlines);
    final ListView listView = (ListView)findViewById(R.id.listv);
    String[] items= {"HCI","ITM","Presentation"};
    arrayList=new ArrayList<>(Arrays.asList(items));
    adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
    listView.setAdapter(adapter);

    txtInput=(EditText)findViewById(R.id.txtinputs);


            if(R.id.listv == 0)
                listView.setBackgroundColor(Color.parseColor("#fffff"));


    });

}

xml

<ListView
    android:id="@+id/listv"
    android:layout_marginTop="100dp"
    android:layout_width="wrap_content"
    android:layout_height="200dp">

</ListView>

You could use a custom ArrayAdapter, override getView() and in it check if "position" == 0 then change the background of the item to what you prefer. I beleive it is called for every item, after notifyDataSetChanged() has been invoked.

This is not the correct approach. Rendering each row happens inside the adapter. You have to define your own adapter or you can extend from ArrayAdapter. In its getView() method, you call the base class getView first and if the position is zero, then you set the background color.

class MyAdapter extends ArrayAdapter<String> {
     View getView(int position, View convertView, ViewGroup parent) {
          View ret = super.getView(position, convertView, parent);
          if (position == 0) {
              ret.setBackground(red);
          } else {
             ret.setBackground(white);
          }
          return ret;
     }
} 

You could also add a header view to accomplish this.

Unless you are required to use ListView it maybe better to consider RecyclerView.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM