无法在android中使用ListActivity

时间:2013-02-03 11:13:29

标签: android listactivity

我想在应用开始时选择ListItem并获取所选项目的文字/值,但我无法做到。

代码

public class MenuList extends ListActivity {

String[] classNames = {"MainActivity", "example"}; 
//private View currentSelectedView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(MenuList.this, android.R.layout.simple_list_item_1, classNames));

}   
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);      
    String itemText= classNames[position];

    Toast.makeText(MenuList.this, itemText, Toast.LENGTH_LONG).show();      
}       
  }

通过这个我得到listItem的文本/值但是我无法预先选择listItem。 任何人都可以告诉我该怎么做..?

1 个答案:

答案 0 :(得分:0)

将选择器设置为ListViewandroid:background="@drawable/list_bg"添加到您的Activity_main.xml中

<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"
    android:background="@drawable/list_bg" >

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

</LinearLayout>

并在您的drawable中创建list_bg.xml,如下所示

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/grey" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@color/blue" android:state_pressed="true"/>
    <item android:drawable="@color/blue" android:state_pressed="false" android:state_selected="true"/>

</selector>