ListView在安卓中是很常用的一个组件之一,那么现在我们做一个水果展示的界面
首先写一个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"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lv"></ListView> </LinearLayout>
然后再写一个xml文件作为listview的子列表
<?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:layout_width="50dp" android:layout_height="50dp" android:id="@+id/image"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/fruit_name" android:layout_gravity="center"/> </LinearLayout>
然后是Mainactivity里面
package com.example.mywillstudy; import android.support.v4.util.ArrayMap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); ListView listView = (ListView)this.findViewById(R.id.lv); final List<Map<String,String>> list = new ArrayList<>(); Map<String, String> map1 = new ArrayMap<>(); map1.put("id",R.drawable.apple+""); map1.put("name","苹果"); list.add(map1); Map<String, String> map2 = new ArrayMap<>(); map2.put("id",R.drawable.banana+""); map2.put("name","香蕉"); list.add(map2); Map<String, String> map3 = new ArrayMap<>(); map3.put("id",R.drawable.putao+""); map3.put("name","葡萄"); list.add(map3); SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.item,new String[]{"id","name"},new int[]{R.id.image,R.id.fruit_name}); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Toast.makeText(MainActivity.this,list.get(i).get("name"),Toast.LENGTH_SHORT).show(); } }); } }
最后我们可以看到这样的一个可以点击获取水果名的列表框