Adapter(適配器的講解)適配器就我自己來看,我覺得這是一個非常重要的知識點,Adapter是用來幫助填出數據的中間橋梁,簡單點說吧:將各種數據以合適的形式顯示在View中給用戶看。Adapter有很多的介面、抽象類、子類可以使用,這裡就我們常用的幾個進行講解BaseAdapter,ArrayA...
Adapter(適配器的講解)
適配器就我自己來看,我覺得這是一個非常重要的知識點,Adapter是用來幫助填出數據的中間橋梁,簡單點說吧:將各種數據以合適的形式顯示在View中給用戶看。Adapter有很多的介面、抽象類、子類可以使用,這裡就我們常用的幾個進行講解
BaseAdapter,ArrayAdapter,SimpleAdapter,為了配合講解這幾個適配器,這裡提前使用一下ListView來展示一下適配器的使用,後面會對ListView進行進一步總結。
一、ArrayAdapter(數組適配器),這個適配器使用有一定的局限性,只能顯示一行文本數據
(1)基本使用實例
佈局文件:
<?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="vertical"> <ListView android:id="@+id/ll1" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout>
Java文件
package com.example.test3; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity{ // 定義要顯示的數據 private String[] datas = {"張三","李四","王五","麻子","小強"}; private ArrayAdapter<String> adapter; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.ll1); // 初始化適配器 adapter = new ArrayAdapter<>(this,android.R.layout.simple_expandable_list_item_1,datas); listView.setAdapter(adapter); } }
效果圖:
(2)實現上面還可以先在res\value下創建一個數組資源的xml文件:arrays.xml,然後在listview中使用entries
3、ArrayAdapter也支持泛型,那麼集合肯定必須的,還可以如下所寫