小編今天跟大家探討新的知識,有關於列表ListView,GridView與Android開發工具自帶的適配器Adapter之間的有着千絲萬縷的關係。
先給大家看看這次代碼執行運行的界面。如下、
小編現在從第一張圖片開講了,這張圖片的實現效果是GridView運用適配器方法實現的。。
步驟1.在在佈局創建兩個xml文件,當然有一個文件是已經創建好了,你只需創建另一個就行了。
activity_main.xml:
<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"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:background="#000000">
<GridView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3" >
</GridView>
</LinearLayout>
這個是設置宮格佈局文件,用GridView標籤即可,主要要點是,必須給控件加id,內容纔可以顯示出來,切記切記。
item_main.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/background_dark"
android:orientation="vertical" >
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="應用"
android:textColor="#ffffff"
android:textSize="16sp" />
</LinearLayout>
這是第二個佈局文件,表示是要在宮格佈局要展示給別人看的佈局,我代碼寫進去的是ImageView圖片和TextView文本,控件豎直向下,缺少這個是不行,必須兩個xml佈局結合纔能有效果界面。
步驟2.
開始編寫src裏面的java文件,這也是最重要一步,執行的方法都在裏頭,容我細講。
先給代碼粘貼過來,在進行詳細的分析
//定義成員變量
private GridView mgrid;
//ListAdapter是simpleAdapter和ArrayAdapter的父類
private ListAdapter mAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
mgrid = (GridView) findViewById(R.id.grid);
//創建List列表
List<Map<String, Object>> ListData = new ArrayList<Map<String, Object>>();
//for循環,目的是得到多個不同的控件
for (int i = 0; i <=20; i++) {
//map泛型
Map<String, Object> map = new LinkedHashMap<String, Object>();
//用.put存入數據
map.put("icon", R.drawable.emoji_054 + i);
map.put("name", "應用" + i);
//將數據添加到List列表
ListData.add(map);
}
//創建適配器
//第一個參數:上下文
//第二個參數:列表的數據
//第三個參數:數據是從哪來,這是從Key傳過來的
//第四個參數:數據到哪裏去,這裏是到item_List佈局中去,用控件設置的ID即可拿到
String[] key = new String[] { "icon", "name" };
int[] layout = new int[] { R.id.img, R.id.text };
mAdapter = new SimpleAdapter(MainActivity.this, ListData,
R.layout.item_main, key, layout);
//發送適配器
mgrid.setAdapter(mAdapter);
}
GridView與適配器Adapter相結合就完成了,從上面的執行代碼我們可以知道,其實這是一個MVC框架,這裏M代表List列表,用於封裝存儲數據,V代表的是佈局文件,主要用來顯示文件,C代表的是適配器Adapter,是於M列表相連,實現把數據傳導給列表,佈局,是個橋樑的意思。這裏的適配器是自身的自配器,自定義適配器有機會再一起學習。
完成了GridView佈局,ListVIew佈局的步驟大致與前者相同,唯一不同點就是,res的layout下的xml文件不一樣,這個小編我就 不多講了,留給大家做練習,也可以當做知識點回顧來做。夜深了,今天就到這裏了,小編要睡覺覺了,明天再見面。