problem to listview android
i've got a listView with some data that i inflated to get some nice background color. The problem is that i want to get some awesome separators and i'm unable to setDividerHeight() d开发者_如何转开发epending on the row's data, because it seems that i can't inflate two views on the same getView() method, here's some code:
public View getView(int position, View convertView, ViewGroup parent){
String myText = getItem(position).toString();
String firstLetter = Character.toString(myText.charAt(0));
if(convertView == null){
convertView = this.inflater.inflate(R.layout.lettersrows, null);
}
TextView tv = (TextView)convertView.findViewById(R.id.label);
tv.setText(this.list.get(position));
tv.setTextSize(25);
convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);
/**This is what i want to do*/
if(!firstLetter.equals("A")){
convertView = this.inflater.inflate(R.layout.letters, null);
ListView lv = (ListView)convertView.findViewById(R.id.letters_listview);
lv.setDividerHeight(3);
}
return convertView;
}
The error i'm getting is a NullPointerException at: tv.setText(this.list.get(position)); I guess that dues to that the convertView is now a ListView that's why it doesn't find where to set the text. How could i fix this problem.
Best regards.
You can use your custom Adapter to inflate as many different types of layout as you want.
For this, you just need to change your getViewTypeCount method to return the type of different views you want (2 in your example, regular item and separator) and adapt your getView() method to chose the correct view type to display.
Everything is explained in this great tutorial
Note: In the tutorial, they do that by implementing a getItemViewType() method. This can be useful in some cases.
精彩评论