我是 Android 新手。我正在尝试使用 AddButton 和 List View 创建 LinearLayout View 。我已经粘贴了下面的代码。但是一旦应用程序启动,它就会退出并显示消息“应用程序意外停止”。有什么线索是我错了吗?
目的: 创建一个顶部带有添加按钮的 ListView 。添加按钮将是静态的, ListView 可滚动。添加按钮用于向 ListView 添加元素。
|__Button_|
| |
|List View|
| |
public class SimpleListActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout mainLayout;
mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
int lHeight= LinearLayout.LayoutParams.FILL_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
//------------------------
Button BtnAdd = new Button(this);
BtnAdd.setWidth(60);
BtnAdd.setHeight(60);
BtnAdd.setFocusable(true);
// BtnAdd.setId(idBtnNext);
BtnAdd.setText("Add Hosts");
mainLayout.addView(BtnAdd, new LinearLayout.LayoutParams(lHeight,lWidth));
String[] mStrings = new String[]{"Android", "Google", "Eclipse"};
// Create an ArrayAdapter, that will actually make the Strings above appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mStrings));
ListView lv = getListView();
//------------------------
mainLayout.addView(lv, new LinearLayout.LayoutParams(lHeight,lWidth));
setContentView(mainLayout);
lv.setOnItemClickListener(new OnItemClickListener() { .......
}
我的 list 文件如下所示。
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SimpleListActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Page1"></activity>
<activity android:name=".Page2"></activity>
<activity android:name=".Page3"></activity>
</application>
最佳答案
您不能采用默认的 ListActivity 的 ListView(即来自 getListView())并将其添加到另一个布局。你会得到一个异常(exception)( View 已经有父级)。如果您想要 ListActivity 的自定义布局,您需要提供一个具有正确 ID 的新 ListView。
改变
ListView lv = getListView();
到
ListView lv = new ListView(this);
lv.setId(android.R.id.list);
关于Android 应用程序在使用 b 的 LinearLayout View 启动时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5445532/