安卓提供了一些自带的布局,使用非常简单。直接看代码吧。
package com.example.linfeng.myapplication;
import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListViewActivity extends Activity { private String[] data = { "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListViewActivity.this, android.R.layout.simple_list_item_single_choice , data); ListView listView = (ListView) findViewById(R.id.lv1); listView.setAdapter(adapter); } }
然后是布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.linfeng.myapplication.ListViewActivity"> <!-- android:choiceMode ="singleChoice"实现单选的关键--> <ListView android:id="@+id/lv1" android:choiceMode ="singleChoice" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout>