How To Change Listview Background And Text Color Without Xml
Solution 1:
In case you want to customize each line of the listview you have to use a custom adapter with custom listview item. Then you can use the "getView" Method to catch each item and position to change colors.
Here is a sample:
publicclassListViewAdapterextendsArrayAdapter<Item> {
private Context context;
privateint itemResourceId;
private ArrayList<Item> items;
publicListViewAdapter(Context context, int layoutId, ArrayList<Item> items) {
super(context, layoutId, items);
this.context = context;
this.itemResourceId = layoutId;
this.items = items;
}
@Overridepublic View getView(int position, View view, ViewGroup parent) {
ViewHolderholder=null;
if (view == null) {
holder = newViewHolder();
LayoutInflaterinflater= (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(itemResourceId, null);
holder.listItem = (TextView) view.findViewById(R.id.item);
view.setTag(holder);
}
elseholder= (ViewHolder) view.getTag();
if (position % 2 == 0)
view.setBackgroundColor(context.getResources().getColor(R.color.listItemEven));
else
view.setBackgroundColor(context.getResources().getColor(R.color.listItemOdd));
Itemitem= items.get(position);
holder.listItem.setText((position+1) + ". " + item.sTitle);
return view;
}
staticclassViewHolder {
TextView listItem;
}
}
Solution 2:
android.R.layout.simple_list_item_1
You have to add an extra parameter to your ArrayAdapter, this will be a CUSTOM XML OF YOUR OWN and the next one will be a textview that is inside that custom layout, that way the array adapter will know which layout to fill and which textview needs to show the data you want to show.
from that xml you can modify background and color. will look something like this:
setListAdapter(new ArrayAdapter<String>(CollegeList.this, R.layout.your_custom_layout, R.id.the-text-view-in-that-layout, nameList));
Solution 3:
You can get the xml for simple_list_item_1 here. You can copy it to your project and modify it, just change the code for your listview to setListAdapter(new ArrayAdapter<String>(CollegeList.this, R.layout.simple_list_item_1, nameList));
You can also create one yourself, since simple_list_item_1 is nothing but a textview. Just make sure that the id is android:id="@android:id/text1"
otherwise it won't work with the default adapter.
Post a Comment for "How To Change Listview Background And Text Color Without Xml"