To do so, you will need to create your own custom adapter. In the getView method (which returns the View to display for each list item), apply the color you want to your TextView's background.
The cool thing about customAdapters is that you can do absolutely anything, and display much more complicated Views for your list items, because you are not restricted to TextViews anymore, you can change your list item XML layout to any kind of View/Layout...
Something like this:
MyAdapter.java
public class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private ArrayList<String> data;
public MyAdapter(Context context, ArrayList<String> data){
// Caches the LayoutInflater for quicker use
this.inflater = LayoutInflater.from(context);
// Sets the events data
this.data= data;
}
public int getCount() {
return this.data.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return this.data.get(position);
}
public long getItemId(int position) throws IndexOutOfBoundsException{
if(position < getCount() && position >= 0 ){
return position;
}
}
public int getViewTypeCount(){
return 1;
}
public View getView(int position, View convertView, ViewGroup parent){
String myText = getItem(position);
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
convertView = this.inflater.inflate(R.id.my_row_layout, null);
}
// Select your color and apply it to your textview
int myColor;
if(myText.substring(0, 1) == "a"){
myColor = Color.BLACK;
}else{
....
}
convertView.findViewById(R.id.myTextViewId).setBackground(myColor);
// Of course you will need to set the same ID in your item list XML layout.
return convertView;
}
}
and then in your activity set the adapter like this:
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> words = populateList();
List<String> l = removeDoubles(words);
Collections.sort(l);
ListView lv = (ListView)findViewById(R.id.listview);
MyAdapter adapter = new MyAdapter(getApplicationContext(), l);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…