1.New 一個 Android Application project 

2.將Project 命名為 ListViewSimple

3. 首先是LayoutMainActivity.java 檔案, 程式碼如下

 

package com.example.listviewsimple;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class LayoutMainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

String[] data = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Linux Mint", "Linux Open", "HTC" };

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

setListAdapter(adapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();
}

}

 

程式解說:

1.將Activity 命名為 LayoutMainActivity (當然的你可以命名想要的Activity name)並繼承ListActivity

public class LayoutMainActivity extends ListActivity

2. Override onCreate()

 

這邊先建立一個要顯示在ListView上面的Data來源

String[] data = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Linux Mint", "Linux Open", "HTC" };

 

然後New一個String 的 array adapter

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

 

ArrayAdapter的API使用可以參考以下網址:

http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context, int, T[])

 

 

最後我們設剛剛new的array adapter給ListView

setListAdapter(adapter);

3.Override onListItemClick()

 

當listview的item被按下後,先取得被按下的item的字串

String item = (String) getListAdapter().getItem(position);

 

以Toast的方式顯示按下的item已經被選中

Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();

其中Toast.LENGTH_SHORT 是控制Taost在畫面上停留的時間

所以如果覺得Toast顯示時間太短可以改成Toast.LENGTH_LONG

 

結果畫面:

 2013-02-28_00-05-32

 

2013-02-28_00-05-39    

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 ArthasTseng 的頭像
    ArthasTseng

    一緒に世界の温度を体験する

    ArthasTseng 發表在 痞客邦 留言(0) 人氣()