显示ListView子项和标题

时间:2013-03-14 04:15:47

标签: java android android-listview android-adapter

我有ListView并且无法在列表中显示子项...它只显示一个或另一个,但不能同时显示两者。如果我从下面删除数字,它将显示字符串(标题):

我想显示项目和子项目。

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.loadData();

    String []titles_str = titles.toArray(new String[titles.toArray().length]);
    this.setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, titles_str));

    Number []subtitles_str = lengths.toArray(new Number[lengths.toArray().length]);
    this.setListAdapter(new ArrayAdapter<Number>(this,
            android.R.layout.simple_list_item_2, android.R.id.text2, subtitles_str));
}

1 个答案:

答案 0 :(得分:4)

你正在使用“this.setListAdapter”两次,只有第二个“this.setListAdapter”会反映出来。

根据您的要求,请使用

1)custom arrayadapter<customObject> 
      or 
2)simpleadapter.

1)使用自定义arrayadapter,请检查http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

2)使用SimpleAdapter:

List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i=0; i<titles_str.length; i++) {
    Map<String, String> datum = new HashMap<String, String>(2);
    datum.put("title", titles_str[i]);
    datum.put("subtitle", String.valueof(subtitles_str[i]));
    data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
                                      android.R.layout.simple_list_item_2,
                                      new String[] {"title", "subtitle"},
                                      new int[] {android.R.id.text1,
                                                 android.R.id.text2});
this.setListAdapter(adapter);