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>