ListView setListAdapter學習實例


import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.database.Cursor;
import android.provider.Contacts.Phones;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
//setListAdapter是ListActivity的一個方法
public class MainActivity extends ListActivity {
	private Button button;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] items = {"one","two","three"};   //設置要顯示的內容
        setContentView(R.layout.activity_main);   
        //ArrayAdapter有三個參數,第一是對象,第二是List的格式,第三個是List的內容。
        setListAdapter(new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1, items)); //綁定視圖和內容並顯示
        button = (Button)findViewById(R.id.button);        
    }
    
    public void onListItemClick (ListView l, View v, int position, long id){
         //得到點擊的視圖位置, 並獲得視圖的顯示內容
         String text = (String)getListView().getItemAtPosition(position); 
    	 button.setText(text);             //在按鈕上顯示所點擊視圖的文本信息
    }
}

以下是XML文件. activity_main.xml

ListView的ID值必須爲@android:id/list, 這樣setListAdapter才能找到這個視圖位置.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    />

<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

</LinearLayout>



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