这是我在主要活动中的代码
public class MainActivity extends ListActivity {
private String [] mainScreenList = {"Portal","Settings","Help","About"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> mainScreen = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1, android.R.id.text1,mainScreenList);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(mainScreen);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
//get selected items
/* if(position==0)
{
Intent i = new Intent(this, DataEntryActivity.class);
startActivity(i);
}else if(position==1)
{
Intent i = new Intent(this, DataEntryActivity.class);
startActivity(i);
}else if(position==2)
{
Intent i = new Intent(this, DataEntryActivity.class);
startActivity(i);
}else if(position==3)
{
Intent i = new Intent(this, DataEntryActivity.class);
startActivity(i);
}*/
}
}
目前我只是想显示所选列表视图项的名称。
这是XML代码
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:id="@android:id/list"
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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.bernine.practicalsessions.MainActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/listView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
</ListView>
在运行应用程序时,它会说&#34;不幸的是应用程序已经停止。&#34;
答案 0 :(得分:0)
签出activity_main.xml
布局文件后。您已将ListView
包含在另一个ListView
中。这是无效的。
在ListView
之类的任何容器中加入LinearLayout ,RelativeLayout , etc.
。对于ListView
,您应该将ID用作@android:id/list
。
一旦查看此样本布局。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>