Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

android - How to set both lines of a ListView using simple_list_item_2?

So the following will create a ListView where the rows have their "primary" textview filled by the values array.

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
    android.R.layout.simple_list_item_2, android.R.id.text1, values);

Changing the third parameter to android.R.id.text2 sets the "secondary" textview. Is there any simple way to set both?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This questions ranks high with Google but I consider the given answer to be way too complicated. As pointed out in other answers, the desired functionality can be achieved using ArrayAdapter with a very easy trick.

You can override the getView method of the ArrayAdapter:

ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_2, android.R.id.text1, list) {
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    TextView text1 = (TextView) view.findViewById(android.R.id.text1);
    TextView text2 = (TextView) view.findViewById(android.R.id.text2);

    text1.setText(persons.get(position).getName());
    text2.setText(persons.get(position).getAge());
    return view;
  }
};

If you didn't notice: the trick is to supply android.R.id.text1 as (principally unneccessary) parameter, otherwise the call to super will cause an exception.

Also, this solution does not make use of TwoLineListItem, which was deprecated in API 17.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...