我正在为包含2个项目(2个textViews)的列表视图创建一个数组适配器。
我知道如何在我的适配器中添加单个项目:
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,R.layout.newsrow, R.id.titleTextView,myArray);
list.setAdapter(listAdapter);
但是我应该怎样做才能在listAdapter中添加第二个textView(在我的应用程序中称为contentTextView)?
答案 0 :(得分:4)
为您的行创建自定义布局。
<强> custom_row.xml:强>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listview_layout">
<TextView
android:id="@+id/listview_firsttextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>
<TextView
android:id="@+id/listview_secondtextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</TextView>
</LinearLayout>
之后您将需要一个自定义ArrayAdapter。为此,您需要扩展ArrayAdapter&lt;&gt; class,示例如下:
public class CustomAdapter extends ArrayAdapter<String>
{
private Context context;
private List<String> strings;
public ListViewAdapter(Context context, List<String> strings)
{
super(context, R.layout.listview_row, order);
this.context = context;
this.strings = new ArrayList<String>();
this.strings = strings;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listview_row, parent, false);
TextView your_first_text_view = (TextView) rowView.findViewById(R.id.listview_firsttextview);
TextView your_second_text_view = (TextView) rowView.findViewById(R.id.list_secondtextview);
your_first_text_view.setText(strings.get(position));
your_second_text_view.setText(strings.get(position)); //Instead of the same value use position + 1, or something appropriate
return rowView;
}
}
在最后的步骤中,将适配器设置为适当的ListView,如下所示:
ListView my_list_view = (ListView) findViewById(R.id.mylistview);
CustomAdapter my_adapter = new CustomAdapter(this, my_strings);
my_list_view.setAdapter(my_adapter);
我希望这能让您了解如何为ListView设置自定义适配器。