2014-2-9AdapterView及其子類1!

0.      AdapterView組件是一組重要組件,AdapterView本身是一個抽象類,它派生的子類在用法上十分相似。AdapterView具有以下特徵:

*AdapterView繼承ViewGroup,本質是容器

*AdapterView可以包括多個“列表項”,並將多個“列表項”以合適的形式顯示出來

*AdapterView顯示的多個“列表項”由Adapter提供。調用AdapterViewsetAdapterAdapter)方法設置Adapter即可

AdapterView派生出三個子類:AbsListView、AbsSpinner和AdapterViewAnimator,這三個子類也是抽象類,實際使用時採用他們的子類。

1.      列表視圖(ListView)和ListActivity

ListView以垂直列表的形式顯示所有列表項。有以下兩種形式創建:

       *直接使用ListView進行創建

       *讓Activity繼承ListActivity(相當於該Activity顯示的組件爲LiestView)

獲得ListView後,就要爲ListView設置它要顯示的列表項。ListView表顯示出AdapterView的特徵:通過setAdapter(Adapte)方法爲之提供Adapter、並由Adapter提供列表項。

實例:ListView

Xml代碼清單

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- 直接使用數組資源給出列表項 -->
    <!-- 設置使用紅色的分隔條 -->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:entries="@array/books"
        android:divider="#080"
        android:dividerHeight="2px"
        android:footerDividersEnabled="false"   
        ></ListView>
</LinearLayout>

PS:android:entries指定了列表項數組,android:divider改變列表項之間的分隔條。

android:entries="@array/books"該屬性用了數組資源,所以需定義一個books數組:

arrays.xml

<?xml version="1.0"encoding="utf-8"?>
<resources>
    <string-array name="books">
        <item>如何閱讀一本書</item>
        <item>理想豐滿</item>
        <item>拆掉思維的牆</item>
        <item>正能量</item>
        <item>遇見未知的自己</item>
        <item>做最好的自己</item>
    </string-array>
</resources>


2.    Adapter接口及實現類

Adapter本身只是一個接口,它派生了ListAdapterSpinnerAdapter兩個接口,其中ListAdapter爲AbsListView提供列表項,而SpinnerAdapter爲AbsSpinner提供列表項。

在這兩個類之下還有許多繼承類,其常用實現類有:

*ArrayDapter:簡單易用的Adapter,常用於數組或List集合的多個值包裝成多個列表項

*SimpleAdapter:功能強大,用於將List集合的多個對象包裝成多個列表項

*SimpleCursorAdapter:與SimpleAdapter相似,用於包裝Cursor提供的數據

*BaseAdapter:常用於被擴展,可以對個列表項進行最大限度的定製

實例:用ArrayAdapter創建ListView

XML代碼清單

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <!-- 設置使用紅線的分隔條 -->
    <ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#f00"
        android:dividerHeight="2px"
        android:headerDividersEnabled="false"></ListView>
    <!-- 設置使用綠線的分隔條 -->
    <ListView
        android:id="@+id/list2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#0f0"
        android:dividerHeight="2px"
        android:headerDividersEnabled="false"></ListView>
</LinearLayout>

Java代碼清單

packagecom.hqsA.arrayadaptert;
 
importandroid.os.Bundle;
importandroid.widget.ArrayAdapter;
importandroid.widget.ListView;
importandroid.app.Activity;
 
public classArrayAdapterT extends Activity {
 
    @Override
    protected void onCreate(BundlesavedInstanceState) {
        super.onCreate(savedInstanceState);
       setContentView(R.layout.array_adapter_t);
        ListView list1 = (ListView) findViewById(R.id.list1);
        //定義一個數組
        String[] arr1 = {"中興", "華爲","酷派", "聯想"};
                    //將數組包裝爲ArrayAdapter
        ArrayAdapter<String> adapter1 =new ArrayAdapter<String>
                    (this,R.layout.array_item, arr1);
        //爲ListView設置Adapter
        list1.setAdapter(adapter1);
        ListView list2 = (ListView)findViewById(R.id.list2);
        //定義一個數組
        String[] arr2 = {"ZTE" ,"Huawei" , "Lenovo" , "Coolpad"};
                   //將數組包裝爲ArrayAdapter
        ArrayAdapter<String> adapter2 =new ArrayAdapter<String>
                    (this,R.layout.checked_item, arr2);
        //爲ListView設置Adapter
        list2.setAdapter(adapter2);
    }
}

Ps:創建ArrayAdapter時必須指定三個參數:

*Context:它代表訪問整個Android應用的接口,幾乎創建所有組件都需要傳入Context對象

*textViewResourceld:資源ID,該資源ID代表一個TextView,該TextView組件將作爲ArrayAdapter的列表項組件

*數組或List:該數組或List爲多個列表項提供數據

Array_item.xml代碼清單

<?xml version="1.0"encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/TextView"
    android:textSize="24dp"
    android:padding="5px"
    android:shadowColor="#f0f"
    android:shadowDx="4"
    android:shadowDy="4"
    android:shadowRadius="2">
</TextView>

Check_item.xml佈局文件與上面相似

效果:

3.    使用SimpleAdapter創建ListView

實例:

Xml代碼清單

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <!-- 定義一個List -->
    <ListView android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

Java代碼清單

public class SimpleAdapterT extends Activity {
 
    private String[] names = new String[]
            {"虎頭", "弄玉" , "李清照" , "李白"};
    private String[] descs = new String[]
            {"可愛的小孩" , "一個擅長音樂的女孩"
            , "一個擅長文學的女性" , "浪漫主義詩人"};
    private int[] imageIds = new int[]
            {R.drawable.tiger , R.drawable.nongyu ,
            R.drawable.qingzhao , R.drawable.libai};
    @Override
    protected void onCreate(BundlesavedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_adapter_t);
        //創建一個List集合,List集合的元素是Map
        List<Map<String , Object>>listItems=
                new ArrayList<Map<String ,Object>>();
        for(int i = 0 ;i < names.length ; i++)
        {
            Map<String, Object> listItem=new HashMap<String, Object>();
            listItem.put("header", imageIds[i]);
            listItem.put("personName", names[i]);
            listItem.put("desc", descs[i]);
            listItems.add(listItem);
        }
        //創建一個SimpleAdapter
        SimpleAdapter simpleAdapter = new SimpleAdapter(this, listItems,
                R.layout.simple_item,
                new String[]{"personName", "header", "desc"},
                new int[]{R.id.name, R.id.header, R.id.desc});
                ListView list = (ListView)findViewById(R.id.mylist);
        //爲ListView設置Adapter
        list.setAdapter(simpleAdapter);
       
    }
}

PS:創建Simple對象需要5個參數,4個關鍵參數爲:

第2個參數:該參數應爲一個List<?extends Map<String,?>>類型的集合對象,該集合中每個Map<String,?>對象生成一個列表項

第3個參數:該參數指定一個佈局界面ID。佈局界面裏定義組件來顯示列表項。

第4個參數:該參數是一個String[]類型的參數,該參數決定提取Map<String,?>對象中的哪些key對應的value來生成列表項

第5個參數:int[]類型的參數,決定填充哪些組件。

Simple_item對應佈局文件代碼

<?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="horizontal">
    <!-- 定義一個ImageView,用於作爲列表項的一部分 -->
    <ImageView android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        />
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
        <!--定義一個TextView,用於作爲列表項的一部分-->
        <TextView android:id="@+id/name"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="20dp"
           android:textColor="#f0f"
           android:paddingLeft="10dp"
           />
        <TextView android:id="@+id/desc"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="14dp"
           android:textColor="#f00"
           android:paddingLeft="10dp"
           />
    </LinearLayout>
</LinearLayout>

爲上面Activity中的ListView綁定事件監聽器

        

//爲ListView的列表項的單擊事件綁定事件監聽器
        list.setOnItemClickListener(new OnItemClickListener()
        {
            //第position項被單擊時激發該方法
            @Override
            public void onItemClick(AdapterView<?> parent,View view,
                    int position, long id)
            {
                System.out.println(names[position]
                        + "被單擊了");
            }
        });
        //爲ListView的列表項的選中事件綁定事件監聽器
        list.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            //第position項被選中時激發該方法
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {
                System.out.println(names[position] + "被選中了");
               
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
               
            }
        });

運行效果:


*PS:選中事件無法發生,只有單擊事件可以正常運行,不知道原因,可能是事件監聽器的問題,以後要查找原因!

4.    擴展BaseAdapter實現ListView

Xml代碼清單

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
</LinearLayout>

JAVA代碼清單

public class BaseAdapterT extends Activity {
 
    ListView mylist;
    @Override
    protected voidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.base_adapter_t);
        mylist = (ListView) findViewById(R.id.mylist);
        BaseAdapter adapter = new BaseAdapter()
        {
 
            @Override
            public int getCount() {
                //指定一共包含40個選項
                return 40;
            }
 
            @Override
            public Object getItem(int position) {
                return null;
            }
            //重寫該方法,該方法的返回值將作爲列表項的ID
            @Override
            public long getItemId(int position) {
                return position;
            }
            //重寫該方法,該方法返回的view將作爲列表框
            @Override
            public View getView(int position, View convertView
                    , ViewGroup parent) {
                //創建一個LinearLayout,並向其中添加兩個組件
                LinearLayout line = new LinearLayout(BaseAdapterT.this);
                line.setOrientation(0);
                ImageView image = new ImageView(BaseAdapterT.this);
                image.setImageResource(R.drawable.ic_launcher);
                TextView text = new TextView(BaseAdapterT.this);
                text.setText("第" + (position +1) + "個列表項");
                text.setTextSize(20);
                text.setTextColor(Color.RED);
                line.addView(image);
                line.addView(text);
                //返回LinearLayout實例
                return line;
               
            }
        };
        mylist.setAdapter(adapter);
    }
}


PS:創建一個BaseAdapter對象,需要重寫如下4個方法:

    *getCount():返回值控制該Adapter將會包含多少個列表項

    *getItem(int position):該方法的返回值決定第position處的列表項內容

    *getItemId(int position):該方法返回值決定第position處的列表項ID

    *getView(int position, View convertView,ViewGroup parent):該方法的返回值決定第position處的列表項組件

       創建Adapter的四種方法:

       (1).ArrayAdapter          (2).基於ListView實現        

       (3).SimpleAdapter               (4).BaseAdapter

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章