嗨我是android的新开发者我已经编写了显示简单对话框的代码,在这个对话框中我已经编辑了文本视图。当我在编辑文本上输入文本然后我改变了scree的方向然后编辑文本的值还没出现!
我编写的代码如下
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
请有人能解决这个问题吗?
答案 0 :(得分:1)
基本上,这涉及覆盖onRetainNonConfigurationInstance方法。 看这里: Faster Screen Orientation Change
摘录:
“Activity类有一个特殊的 方法叫做 onRetainNonConfigurationInstance()。 这个方法可以用来传递一个 任意对象你未来的自我和 Android很聪明,可以称之为 方法仅在需要时。在这种情况下 Photostream,使用的应用程序 这个方法传递下载的 图像到未来的活动 方向改变。“
答案 1 :(得分:1)
prasad ... editText框没有ID,如果视图元素没有ID,当用户更改手机的方向时,视图状态不会自动保存在软杀死中。您可能最好使用XML布局创建自定义对话框,然后编辑文本框应该具有ID,并且视图状态应该在软杀死时自动保存。
JAL
我有一些代码here。
编辑:从Android文档中获取的原型代码几乎无法运行,因为我没有时间处理此问题。在res / layout中创建一个XML布局作为alert_dialog_text_entry.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">
<EditText android:text="Stateful"
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</LinearLayout>
然后使用此布局创建警报:
AlertDialog.Builder builder= new AlertDialog.Builder(this);
LayoutInflater inflater= getLayoutInflater();
final View myView= inflater.inflate(R.layout.alert_dialog_text_entry, null);
builder.setTitle("About");
builder.setMessage(alertMessage+"Version: "+versionName);
builder.setView(myView);
AlertDialog alert= builder.create();
由于editText框有一个ID,它似乎可以在软杀死时保存状态。
答案 2 :(得分:0)
这个问题很老,但仍然值得给出一个更简单的答案。 JAL提到需要设置ID,但您可以直接在Java中执行此操作。例如,将以下新行添加到上面的原始代码中:
// Set an EditText view to get user input
final EditText input = new EditText(this);
// Id the EditText so the framework will save/restore it for us
input.setId(R.id.my_id_for_alert_box_inputs); // <-------- New line
alert.setView(input);
在/res/values
下创建一个名为ids.xml
的新XML文件。在那里,定义我们在Java中使用的id:
<?xml version="1.0" encoding="utf-8"?>
<!-- Integer IDs used for tagging Views made in Java programmatically
without clashing with XML-defined views. -->
<resources>
<!-- Used to id the input box in a dialog. Reused in different dialogs. -->
<item type="id" name="my_id_for_alert_box_inputs" />
</resources>
这是有效的,因为Android应用程序框架应该保存/恢复已定义ID的视图。上面的整个XML部分很整洁,但并不是真的需要。您可以将一个已组成的整数插入到Java View.setId()
调用中,以使其成为一行修复。