關於SimpleAdapter和ListView結合使用,實現列表視圖的筆記,simpleadapter
使用ListView需要為其添加適配器:
適配器有兩種:1.ArrayAdapter --用於單獨文字顯示
2.SimpleAdapter --用於文字和圖片顯示
這裡主要記錄SimpleAdapter:
先看SimpleAdapter的建構函式:
SimpleAdapter(context,data,resource,from,to)
--context:上下文,其實就是指的activity本身
--data:資料來源:一個包含了map的List集合;List裡的每一個元素都是一個Map集合,Map是包含多組索引值對
--resource:布局檔案,可以自己寫,在R.Layout下可以獲得,布局中對應元素的總和,全部可以儲存在Map中
--from:一個String[]數組,對應Map中的key元素的,類似於起名字
--to:在從Map中擷取對應key的值後,儲存進去具體的值
下面是具體的例子
工具:Android studio
首先寫布局檔案:item.xml,存放在layou檔案夾下
<?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/itempic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:src="@mipmap/ic_launcher" /> <TextView android:id="@+id/itemtext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="demo" android:textSize="40sp" /></LinearLayout>
在MainActivity下執行個體接收ListView和SimpleAdapter對象
private ListView listView; // private ArrayAdapter<String> adapter; private SimpleAdapter si_adapter; //list集合是抽象集合,執行個體化其執行個體對象ArrayList private List<Map<String,Object>> simpleData; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView)findViewById(R.id.listView); simpleData=new ArrayList<Map<String,Object>>(); si_adapter=new SimpleAdapter(this,getData(),R.layout.item,new String[]{"pic","text"},new int[]{R.id.itempic,R.id.itemtext}); listView.setAdapter(si_adapter); }
上面的getdate()方法:
public List<Map<String,Object>> getData(){ for(int i=0;i<20;i++){ Map<String,Object> map=new HashMap<String,Object>();
//填入真實的pic資訊 map.put("pic",R.mipmap.ic_launcher);
//填入真實的text資訊 map.put("text","機器人"+i+"號"); simpleData.add(map); } return simpleData; }
將SimpleAdapter適配器添加到ListView中去。
分析:SimpleAdapter對資料的解析
布局檔案:決定的資料的視圖化呈現方式
from:為每一個元素限定一個特定的符號
to: 每一個元素在XML中的對應情況
data:資料來源,將用於被解析