【发布时间】:2012-02-09 08:03:04
【问题描述】:
我正在编写我的第一个 Android 应用程序,并且我有一个要显示两个单独对话框的活动:
Dialog A - 一个简单的 AlertDialog,显示文本并被关闭 对话框 B - 带有 EditText 和保存和取消按钮的“另存为”弹出窗口
我找到了有关创建 AlertDialogs 和自定义对话框的教程,并且我已经能够让它们中的每一个工作,但只能单独工作。当我尝试将所有代码放入 onCreateDialog 方法中的 switch/case 语句时,启动 AlertDialog 时应用程序崩溃。
这是我的 onCreateDialog 代码:
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
// Display dialog
case 0:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage(messageText);
alertDialog.setNegativeButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
return alertDialog.create();
// Save As dialog
case 1:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.save_as);
dialog.setTitle("Save as:");
Button cancel = (Button)findViewById(R.id.cancel);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
return dialog;
}
return null;
}
这两种情况都可以自己工作,但是当我把这两种情况都放进去时应用程序崩溃了。
这是自定义对话框布局的 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:text="Save this list as:"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/list_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@android:drawable/bottom_bar"
android:paddingLeft="4.0dip"
android:paddingTop="5.0dip"
android:paddingRight="4.0dip"
android:paddingBottom="1.0dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/save"
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:text="Save"
android:layout_weight="1.0"
></Button>
<Button
android:id="@+id/cancel"
android:layout_width="0.0dip"
android:layout_height="fill_parent"
android:text="Cancel"
android:layout_weight="1.0"
></Button>
</LinearLayout>
</LinearLayout>
我应该只使用一种格式还是另一种格式?我还读到现在首选 DialogFragments,但我还没有找到任何好的新手级教程。任何建议将不胜感激。
【问题讨论】:
-
附录:AlertDialog 由于我已修复的非法参数异常而崩溃。无论如何,自定义对话框都会崩溃,即使我从未启动 AlertDialog。如果情况 0 不存在,它会起作用。
-
我想出了一部分。这两个对话框确实在 switch/case 语句中起作用。 AlertDialog 由于非法参数异常而崩溃,并且自定义对话框在 cancel.setOnClickListener 处崩溃。我尝试拉入我的 EditText 并在其上使用 setText() 方法,但它也崩溃了,因此对话框的设置器似乎存在问题。我会对此做更多的研究。
-
膨胀布局消除了崩溃,但设置器还没有工作。
-
通过创建一个新类并扩展 Dialog 让一切正常工作。哦,快乐的一天!我妈妈会很自豪的。
标签: android-dialog