ListView setListAdapter学习实例

这篇博客探讨了在Android中如何使用ListView并详细解释了setListAdapter方法的用法。主要内容包括XML布局文件activity_main.xml的设计,其中指出ListView的ID必须设置为@android:id/list以确保适配器能正确绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值