Android應(yīng)用界面開(kāi)發(fā)
第二章學(xué)習(xí)
第一部分####
1.Adapter適配器是什么
所謂適配器,是一個(gè)在“用戶(hù)界面”View和“數(shù)據(jù)模型”Model之間的"控制器"Controller
也就是說(shuō),他是個(gè)翻譯官,為兩邊做個(gè)翻譯。
Adapter其中之一,最簡(jiǎn)單的ArrayAdapter,其實(shí)也不簡(jiǎn)單,
其中一種構(gòu)造方法如下:
public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
throw new RuntimeException("Stub!");
}
其中包含4條構(gòu)造參數(shù)
Context context:上下文
int resource:項(xiàng)布局
int textViewResourceId:數(shù)據(jù)要顯示的控件的id
T[] objects:數(shù)據(jù)源
為了完成以上的最簡(jiǎn)單的適配器,我們起碼需要做以下幾件事:
創(chuàng)建一個(gè)數(shù)據(jù)源,暫且定義一個(gè)String[] 數(shù)組作為數(shù)據(jù)源
private String[] data = {"北京","上海","廣州","深圳"};
創(chuàng)建一個(gè)xml布局文件,命名 list_item.xml
在此布局內(nèi)新建一個(gè)textview用于放置數(shù)據(jù)源中對(duì)應(yīng)的文字
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用于顯示內(nèi)容"
android:textSize="30sp"
android:id="@+id/tvCity"/>
好了,準(zhǔn)備完成,可以為ArrayAdapter實(shí)例化了
ArrayAdapter<String> Adapter = new ArrayAdapter<>(this, R.layout.list_item, R.id.tvCity, data);
但是”Controller“和數(shù)據(jù)源”Model“都有,還缺一個(gè)“View”啊。
主界面的xml里新建一個(gè)ListView吧
<ListView
android:id="@+id/lvMsg"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
名字改一下 lvMsg為了方便找到他,然后回java中去關(guān)聯(lián)這個(gè)ListView
private ListView mTvMsg = (ListView) findViewById(R.id.lvMsg);
然后使用setAdapter語(yǔ)句將ListView跟Adapter關(guān)聯(lián)起來(lái)
mTvMsg.setAdapter(Adapter);
大功告成,最最簡(jiǎn)單的一個(gè)ListView完成啦!(等等……不是在講Adapter嗎?)
哦天哪,Adapter還有好多好多類(lèi)
、
常見(jiàn)的介紹下:
- BaseAdapter:抽象類(lèi),實(shí)際開(kāi)發(fā)中我們會(huì)繼承這個(gè)類(lèi)并且重寫(xiě)相關(guān)方法,用得最多的一個(gè)Adapter!
- ArrayAdapter:支持泛型操作,最簡(jiǎn)單的一個(gè)Adapter,只能展現(xiàn)一行文字~
- SimpleAdapter:同樣具有良好擴(kuò)展性的一個(gè)Adapter,可以自定義多種效果!
- SimpleCursorAdapter:用于顯示簡(jiǎn)單文本類(lèi)型的listView,一般在數(shù)據(jù)庫(kù)那里會(huì)用到,不過(guò)有點(diǎn)過(guò)時(shí), 不推薦使用!
額,,各位就自己研究下吧。