[Android]ListView & ArrayAdapter介紹與使用

ListView 是一個可捲動的顯示清單物件的View
我們可以利用Adapter來將資料載入並顯示出來
Android Developer上對Adapter的概觀是這麼說的:
An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.
意思大概是 Adapter物件是View的底層資料與AdapterView之間溝通的橋樑
Adapter除了提供存取物件資料外,也管理為資料集合裡的每個物件創建View。
((破英文見諒

Android API提供了一些Adapter 像是BaseAdapter、ListAdapter等
以下是以一個ArrayAdapter做為範例
首先先從palette拉一個ListView隨便放
參考程式碼如下:

public class MainActivity extends AppCompatActivity {
private ListView list;
private String[] str = {"item1","item2","item3","item4","item5"};
private ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.show_lv);
arrayAdapter = new ArrayAdapter(this,R.layout.listitem_layout,str);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"Item "+String.valueOf(position)+" clicked!!",Toast.LENGTH_SHORT).show();
}
});
}
}
12行宣告一個ArrayAdapter       建構子如下:
ArrayAdapter(Context context, int resource, T[] objects)
context 是你應用程式context
resource List裡item的layout
object 為你要載入的資料

接著13行為ListView指定Adapter
然後14行設定當清單物件點擊的Listener並覆寫onItemClick方法
將你想要在清單物件被點擊時做的事寫在裡面

關於resource  我們需要另外建立一個layout來顯示文字
在res/layout目錄中按右鍵->new->layout resource file
輸入file name後按確定
接著打開剛剛建立的layout file
點左下角Text分頁((在Design旁
參考內容如下
<textview android:gravity="center"
android:id="@+id/list_item"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
</textview>
其中比較需要注意的是第3行
xmlns 是xml命名空間的宣告  如果不加或輸入錯誤會顯示找不到屬性之類的錯誤
更詳細的介紹會另外再發一篇文章

接著就可以執行看看結果~

如有錯誤還請大大們指教

留言

這個網誌中的熱門文章

[android]QR code掃描