ListView与ArrayAdapter一起使用,ArrayAdapter为ListView提供内容(包括ListView的布局和items)
举个例子:
ListView listView;
String[] msgList = {''a","b","c","d"};
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, R.layout.msg_item, msgList);
listView.setAdapter(adapter);
其中MainActivity是本Activity的类名.
R.Layout.msg_item是布局文件,可以自己定义布局文件来显示ListView,如我这里自定义布局文件msg_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:id="@+id/left_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left">
<TextView
android:id="@+id/left_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textColor="#fff"/>
</LinearLayout>
<LinearLayout
android:id="@+id/right_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<TextView
android:id="@+id/right_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textColor="#fff"/>
</LinearLayout>
</LinearLayout>
msg_list为ListView提供Item,可以自定义Msg类,不局限于String类型.(List<Msg> msgList)
一般自定义Msg类型是与自定义布局文件msg_item.xml相匹配.
如你想让ListView显示item的形式为:Imageview + TextView,那么你就要定义Msg类,包含:
private int resourceImageId; //对应image的资源id;
private String msg;
然后你的adapter也要重新定义(extends ArrayAdapter<Msg>),重写getView方法:
imageview.setImageResource(Msg.resourceImageId);
textview.setText(Msg.msg);
上面是伪代码,具体实现也不难.