ListView的简单使用
- ListView是学android必学内容之一,主要是将数据填充到布局并响应用户点击等操作。
- 这个例子只是将用数组保存的数据填充到布局,结合了SimpleAdapter来使用,看看效果图:
实现起来也不难,以下为MainActivity的代码
public class MainActivity extends Activity {
private String[] names=new String[]{"邓艾","姜维","鲁肃","陆逊","吕蒙","司马懿","许褚","张角","赵云","诸葛"};
private String[] says=new String[]{"偷渡阴平,直取蜀汉","女等小儿,可敢杀我","合纵连横,方能以弱胜强","吾生脱俗,不为贪逸淫乐之事","留得青山在,不怕没柴烧",
"出来混,迟早要还的!","脱!谁来与我大战三百回合","苍天已死,黄天当立,岁在甲子,天下大吉"," 吾乃常山赵子龙也","观今夜天象,知天下大事"};
private int[] images=new int[]{R.drawable.dengai,R.drawable.jiangwei,R.drawable.lushu,R.drawable.luxun,R.drawable.lvmeng,R.drawable.simayi,R.drawable.xuchu,R.drawable.zhangjiao,R.drawable.zhaoyun,R.drawable.zhuge};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
for(int i=0;i<names.length;i++){
Map<String,Object> showitem=new HashMap<String, Object>();
showitem.put("image",images[i]);
showitem.put("name", names[i]);
showitem.put("say",says[i]);
list.add(showitem);
}
SimpleAdapter sim=new SimpleAdapter(this, list,
R.layout.list,new String[]{"image","name","say"},
new int[]{R.id.image,R.id.name,R.id.say});
ListView listView=(ListView)findViewById(R.id.lv);
listView.setAdapter(sim);
}
}
list.xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<ImageView android:id="@+id/image"
android:layout_width="64dp"
android:layout_height="64dp"
android:baselineAlignBottom="true"
android:paddingLeft="8dp"
/>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:textColor="#ff3"
android:textSize="22sp"
/>
<TextView android:id="@+id/say"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:textColor="#888"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
activity_main.xml布局
<?xml version="1.0"?>
<RelativeLayout tools:context="com.example.lesson_listview1.MainActivity"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/lv"/>
</RelativeLayout>