Android中Adapter我是這麼理解的,是數據和視圖之間的橋樑,數據在adapter中做處理,然後顯示到視圖(ListView)上面。
Adapter有很多種,有ArrayAdapter<T>, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, WrapperListAdapter.
我在項目中用到過的就ArrayAdapter<T>, (數組適配器也可以是對象數組適配器),BaseAdapter(所有Adapter的基類),SimpleAdapter,CursorAdapter(數據來源是cursor)。
ArrayAdapter
本文主要講解ArrayAdapter的創建方法,我把ArrayAdapter分爲三種:簡單的、樣式豐富的但內容簡單的、內容豐富的。
簡單的ArrayAdapter
主函數:
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private ArrayAdapter arrayAdapter;
private SimpleAdapter simpleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView= (ListView) findViewById(R.id.listview);
//1、新建一個適配器
//ArrayAdapter(上下文,當前ListView加載的每一個列表項所對應的佈局文件,數據源)
String [] data={"文本一","文本二","文本三","文本四","文本五","文本六"};
//適配器加載數據源
arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
//視圖(ListView)加載適配器
mListView.setAdapter(arrayAdapter);
}
}
佈局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>