天天看點

android組建學習: ListView與ArrayAdapter

實驗案例4-2 ListView與ArrayAdapter

【實驗目的】

    1.掌握ListView直接通過控件屬性android:entries指定要顯示的字元串數組資料的方法。

    2.掌握ListView通過ArrayAdapter關聯資料的方法

    3.掌握自定義清單項目布局及其使用

    4.掌握清單項目點選事件處理

【實驗原理】

ListView控件以垂直清單的方式顯示清單項目,清單項目的布局是可以根據需要進行設定的。

圖1

    如圖1所示,此ListView中包含了從0到8,共9個清單項目,這個9個清單項目是從上往下垂直顯示的。每個清單項目中,有多個控件(如圖1的TextView、Button),清單項目中的控件的排列方式是指定的布局(清單項目布局)進行控制。

    ListView是用來顯示資料的,那麼,ListView如何與要顯示的資料關聯呢?關聯的方式有二種:

    第一種方式:在ListView中直接指定。這種方式隻适用于簡單的字元串數組資料;

    第二種方式:通過Adapter與資料關聯。常用的Adapter有ArrayAdapter、SimpleAdapter、BaseAdapter等。

【實驗内容】

效果圖:

android組建學習: ListView與ArrayAdapter
android組建學習: ListView與ArrayAdapter

實驗内容

練習一:ListView直接與字元串資料資料相關聯    2

練習二:ListView通過ArrayAdapter關聯資料    4

練習三:自定義ListView項目清單布局    6

練習四:清單項目點選事件處理    8

練習一:ListView直接與字元串資料資料相關聯

圖2

【練習目的】

    掌握ListView直接通過控件屬性android:entries指定要顯示的字元串數組資料的方法。

【内容說明】

    本練習的任務如下:

(1)在資源檔案中建立一個字元串數組作為要顯示的資料;

(2)然後在主布局檔案添加ListView控件,并通過設定ListView的android:entries指定要顯示的字元串數組,這樣将ListView與資料相關聯;

(3)在Activity中加載主布局檔案,實作ListView的顯示。

【練習步驟】

1.建立新項目

先建立一個空項目,如HelloWorld項目,然後進行以下修改。

2.建立顯示資料

修改res/value目錄下的strings.xml檔案,使其内容如下:

<resources>

    <string name="app_name">ListViewDemo</string>

    <string-array name="TennisPlayer" >

        <item>費德勒</item>

        <item>納達爾</item>

        <item>德約科維奇</item>

        <item>穆雷</item>

    </string-array>

</resources>

其中,字元串數組就是要顯示的資料。

3.設定主布局檔案

    修改主布局檔案activity_main.xml,在其中添加ListView元件,并設定其相關屬性,具體内容如下。

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="網球運動員:"

        android:textSize="20sp"

        android:textColor="#FF0000"

        />

    <ListView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:entries="@array/TennisPlayer"

        android:divider="#0000FF"

        android:dividerHeight="1dp" />

</LinearLayout>

請注意:這裡選用了線性布局,在ListView中通過屬性android:entries指定要顯示的資料内容為字元串數組TennisPlayer。

4.編寫代碼

    由于直接在ListView中指定了資料,不需要另外編寫代碼,直接使用Helloworld項目中預設的加載布局檔案的代碼即可。

5.驗證效果

運作,便會出現如圖2的效果。

練習二:ListView通過ArrayAdapter關聯資料

【練習目的】

    掌握ListView通過ArrayAdapter關聯到資料的方法。

【内容說明】

    本練習的任務如下:

(1)在主布局檔案添加ListView控件,并設定其id等屬性;

(2)設定清單項目的布局,(如果使用系統自帶的布局檔案,這步可省略);

(3)在程式代碼中,建立要顯示的資料,即數組資料;

(4)建立與資料、清單項目布局關聯的ArrayAdapter對象; 

(5)擷取ListView控件對象,并将其與上一步的ArrayAdapter對象相關聯;

【練習步驟】

    通過ArrayAdapter實作與練習一相同的效果。

1.建立新項目

先建立一個空項目,如HelloWorld項目,然後進行以下修改。

2.設定主布局檔案

    在主布局檔案activty_main.xml中,添加ListView元件,并設定其相關屬性。具體如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/activity_main"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="網球運動員:"

        android:textSize="20sp"

        android:textColor="#FF0000"

        />

    <ListView

        android:id="@+id/lv"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:divider="#0000FF"

        android:dividerHeight="1dp"

        />

</LinearLayout>

3.編寫代碼

    建立數組資料;建立ArrayAdapter對象,并将其與清單項目布局(此處使用系統自帶的布局)與數組資料關聯;擷取ListView元件對象,并将之與ArrayAdapter對象關聯。具體代碼如下:

package com.example.administrator.mytoast;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private String[] strs = {"費德勒","納達爾","德約科維奇","穆雷"};

    private ListView listview;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,strs);

        listview=(ListView)findViewById(R.id.lv);

        listview.setAdapter(adapter);

    }

}

說明:

(1)android.R.layout.simple_expandable_list_item_1,是系統自帶的布局。其中,隻包含一個TextView元件。

android系統為了友善開發人員,在系統中定義了很多的布局檔案。系統自帶布局檔案所在目錄,我的電腦為:

C:\Program Files\Android\Android Studio\plugins\android\lib\layoutlib\data\res\layout

系統布局檔案和我們自定義的布局在寫法用字首android以示差別:

系統布局檔案:android.R.layout.xxx;

使用者自定義布局檔案:R.layout.xxx;

(2)ArrayAdapter的構造函數

ArrayAdapter有多個構造函數,本例使用的是最常用的一種。

ArrayAdapter(Context context, int resource, T[] objects))

context:上下文

textViewResourceId:清單項目的布局檔案id。對于ArrayAdapter,此清單項目布局中必須要有有一個TextView控件,用來填充資料。可以是系統自還布局,也可以是自定義布局。

objects:資料源(數組或集合)。

4.驗證效果

運作,效果如圖2所示。

練習三:自定義ListView項目清單布局

【練習目的】

掌握自定義項目子布局的使用

【内容說明】

    本練習的任務如下:

(1)在res/layout目錄下,自定義清單項目布局檔案;

(2)在程式代碼中,建立要顯示的資料,即數組資料;

(3)建立與資料、清單項目布局關聯的ArrayAdapter對象; 

(4)擷取ListView控件對象,并将其與上一步的ArrayAdapter對象相關聯;

【練習步驟】

ArrayAdapter也可以使用自定義的清單項目布局檔案。

1.自定義清單項目布局檔案listitem.xml

在res/layout目錄下,建立布局檔案listitem.xml,其内容如下:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"   >

    <TextView

        android:id="@+id/item"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true" 

        android:textSize="18sp" />

    <Button

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:text="測試" />

</RelativeLayout>

在這個清單項目布局中,每個項目加了一個按鈕Button。

2.編寫代碼

    将上面的代碼改寫成如下:

package com.example.administrator.mytoast;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private String[] strs = {"費德勒","納達爾","德約科維奇","穆雷"};

    private ListView listview;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.item,strs);

        listview=(ListView)findViewById(R.id.lv);

        listview.setAdapter(adapter);

    }

}

其實,隻修改了一條語句,即:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

 R.layout.listitem, R.id.item, strs);

說明:

ArrayAdapter構造函數之一:

ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)

    Context:上下文

Resource:包含一個TextView控件的布局檔案的資源ID

textViewResourceId:在布局檔案中被填充的TextView的Id

objects:資料源,可以是一個數組或一個List

3.驗證效果

    運作,得到如圖3的效果

圖3

練習四:清單項目點選事件處理

【練習目的】

掌握清單項目點選事件處理及其實作

【内容說明】

    如果想要在上面的實作清單項目的點出事件處理,可以通過監聽器對點選事件進行監聽,來實作對清單項目被點選時,進行對應的事件處理。

    下面實作,當清單中的某一項被點選時,彈出提示框中顯示:點出了第*項,文本内容為***,ID為*

【練習步驟】

1.設定項目子布局檔案

    在前面的項目布局檔案listitem.xml中,添加一個屬性。具體如下:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent" 

android:descendantFocusability="blocksDescendants"   >

    <TextView

        android:id="@+id/item"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true" 

        android:textSize="18sp" />

    <Button

        android:id="@+id/button1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:text="測試" />

</RelativeLayout>

    添加了android:descendantFocusability="blocksDescendants"

    為什麼要添加這個屬性呢?

    因為項目布局檔案中,包含了Button這個同樣需要監聽點選事件的元件,android:descendantFocusability屬性是用于設定當一個為view擷取焦點時,定義viewGroup和其子控件兩者之間的關系。對于本例,即用于設定清單項item與其中的子控件Button兩者之間擷取焦點的關系。

此屬性的值有三種:

        beforeDescendants:viewgroup會優先其子類控件而擷取到焦點

        afterDescendants:viewgroup隻有當其子類控件不需要擷取焦點時才擷取焦點

        blocksDescendants:viewgroup會覆寫子類控件而直接獲得焦點

    如果清單項目布局中,沒有Button,隻有一個TextView控件,則可不加此項。

2.編寫代碼    

本例在前面代碼的基礎上,加上事件處理代碼,本例的事件處理是通過匿名内部類的方式實作。具體代碼如下:

package com.example.administrator.mytoast;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private String[] strs = {"費德勒","納達爾","德約科維奇","穆雷"};

    private ListView listview;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.item,strs);

        listview=(ListView)findViewById(R.id.lv);

        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //通過view擷取其内部的元件,進而進行操作

                String text = (String) ((TextView)view.findViewById(R.id.item)).getText();

                //大多數情況下,position和id相同,并且都從0開始

                String showText = "點選第" + position + "項,文本内容為:" + text + ",ID為:" + id;

                Toast.makeText(MainActivity.this, showText, Toast.LENGTH_LONG).show();

            }

        });

    }

}

說明:

onItemClick(AdapterView<?> parent, View view, int position, long id)

parent:使用者所點選的AdapterView,這個參數一般不用。

view:目前點選的清單項所對應的布局View對象,可通過這個參數獲得相應的清單項内部的元件,進而對其進行操作。舉個例子,假設有一個ListView,含有4個清單項,你點了第2個,那麼通過view你就可以操作第2個清單項裡面的TextView、ImageView等等的元件(假設存在)。

position:目前點選的清單項的位置,從0開始,也就是點選第n個,position就是n-1。

id:目前點選的清單項的序号,也是從0開始,一般情況下position和id是一樣的。

3.驗證效果

    運作,點選某一項,效果如圖4所示。

圖4

繼續閱讀