close

有時候需要將資料一筆一筆的列在手機畫面上,尤其是從資料庫讀取資料的時候,這時候 ListView 呈現方式就派上用場了。

ListView 只是清單呈現方式,呈現的資料需要使用 Adapter 來傳遞。

主要有三個步驟:

步驟一: 在 layout (XML) 建立 ListView 欄位,如下列的 Line 12 - 16。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ken_chen.exlistview.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView">
</ListView>
</RelativeLayout>
view raw gistfile1.txt hosted with ❤ by GitHub

 

步驟二: 在主程式建立 ListView,並且利用 findViewById 方式取得 layout 上的元件,如下的 Line 9 與 LIne 15。

步驟三: 建立 ArrayAdapter 來傳遞矩陣字串,在下述的 Line 10 是我們要呈現的資料。Line 17 則是建立一個 ArrayAdapter,三個參數分別為 Context (activity), Layout版面, 傳遞的資料

步驟四: Line 18, 將它丟到 listView 物件中。

package com.example.ken_chen.exlistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private ListView listView = null;
String func [] = {"綜藝節目","旅遊節目","政治節目","新聞","關閉APP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,func);
listView.setAdapter(adapter);
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

 

 

結果如下:

listView.jpg

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 葛瑞斯肯 的頭像
    葛瑞斯肯

    葛瑞斯肯樂活筆記

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()