试试这个,使用 android simple_list_view_1
public class MainActivity extends Activity {
static final String[] FRUITS = { "Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple" };
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_fruit);
ListView listView = (ListView) findViewById(R.id.list_fruit);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, FRUITS);
listView.setTextFilterEnabled(true);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
或者在其中定义一个带有 textview 的 list_item.xml,例如:
MainActivity.java
public class MainActivity extends Activity {
static final String[] FRUITS = { "Apple", "Avocado", "Banana", "Blueberry",
"Coconut", "Durian", "Guava", "Kiwifruit", "Jackfruit", "Mango",
"Olive", "Pear", "Sugar-apple" };
private ListView listView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_fruit);
listView = (ListView) findViewById(R.id.list_fruit);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.textView1, FRUITS);
listView.setTextFilterEnabled(true);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
listView.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
}
});
}}
list_fruit.xml
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list_fruit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
</ListView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>