Android DialogFragment在屏幕旋转之后,输入框内的文字消失的原因

来源:互联网 发布:淘宝网店宝贝图片尺寸 编辑:程序博客网 时间:2024/05/22 06:19

在刚开始学习DialogFragment时,创建了一个测试的DialogFragment:

public class TestDialogFragment extends DialogFragment{    @NonNull    @Override    public Dialog onCreateDialog(Bundle savedInstanceState){        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());        return builder.setView(R.layout.test_dialog).create();    }}

布局文件为:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:gravity="center_horizontal"              android:layout_width="wrap_content"              android:layout_height="wrap_content">    <EditText        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <Button        android:text="OK"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

然后在测试的Activity里点击按钮显示DialogFragment,输入文字,如图:

dialogframent

然后旋转屏幕发现对话框没有消失,但是输入的信息却不见了:

这里写图片描述

没办法,只能找原因,看问题出在哪里。通过对比自己和网上demo的布局文件,分析发现:我为了快速测试dialog的效果,写布局时并没有给EditText添加id,这就是问题产生的根本原因。当我加上id之后:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:gravity="center_horizontal"              android:layout_width="wrap_content"              android:layout_height="wrap_content">    <EditText        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/>    <Button        android:text="OK"        android:layout_width="wrap_content"        android:layout_height="wrap_content"/></LinearLayout>

再次测试发现输入的文字就不会消失了。

阅读全文
0 0
原创粉丝点击