如何在方向更改中解除片段中的对话框?

时间:2016-01-10 16:44:14

标签: android android-fragments dialog

我的片段很简单:

    public class Fragment1 extends Fragment  implements OnClickListener{

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View v = inflater.inflate(R.layout.layout_fragment_1, container, false);

        bt = (Button) v.findViewById(R.id.button1);
        bt.setOnClickListener(this);
            return v;
        }


        private void buildAlertDialog() {
            private void buildAlertDialog() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.activity_second);
        dialog.show();
        dialog.getWindow().setLayout((6 * width) / 7, (2 * height) / 5);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.button1:
            buildAlertDialog();
            break;

        default:
            break;
        }
    }
        }

我的活动:

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}}

正如您所看到的,我没有设置任何保存状态,但是当我旋转设备时,对话框一直显示出来。我想要的是解雇它。我该怎么办?请帮我!谢谢!

2 个答案:

答案 0 :(得分:1)

通常情况下它会消失,也许是因为当设备轮换onCreateView()时,您会在onCreateView()显示对话框并再次显示对话框。
您可以通过单击或任何内容显示对话框,或者如果之前显示对话框,则使用标记保留。

<强>更新
在此

中更改对话框widthheight
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        int screenWidth = (int)(display.getWidth() * 6)/7;
        int screenHeight = (int)(display.getHeight() * 2)/7;
        lp.width = screenWidth;
        lp.height = screenHeight;
        dialog.getWindow().setAttributes(lp);

答案 1 :(得分:0)

当您旋转设备时,会重新创建激活,因此会再次显示该对话框,您需要做的就是通过在清单文件中添加以下代码来添加阻止

android:configChanges="orientation"

请参阅:Android Dialog reopen after rotate device