搜尋此網誌

2011年8月19日 星期五

ListView運用

package com.demo.android;

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

//繼承ListActivity 這個類別其實就是一個含有一個ListView元件的Activity類別
public class ListviewtestActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//取得儲存在string.xml的文字 放在countries陣列
String[] countries = getResources().getStringArray(R.array.functionS_array);
// 將陣列的內容 放到ArrayAdapter
rrayAdapter<String> adapter=(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries));

//取得the activity 的list view widget.
ListView lv = getListView();
//設定adapter將陣列內容給這個widget
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
//監聽有沒有click動作
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{

public void onItemClick(AdapterView<?>adapterView, View v, int position, long id)
{
//如果要顯示user選中的內容可以改寫以下
/*Toast.makeText(ListviewtestActivity.this, "You select "+countries[position]+"é �", Toast.LENGTH_SHORT).show();*/

Toast.makeText(ListviewtestActivity.this, "You select "+Integer.toString(position+1), Toast.LENGTH_SHORT).show();
}


});

}
}

main.xml:
//用ListView Widget
<?xml version="1.0" encoding="UTF-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/lv">
</ListView>