Bụng Bự
Bụng Bự

Reputation: 553

How can I dismiss dialog in fragment on orientation change?

My fragment is just simple like this:

    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;
        }
    }
        }

And my activity:

public class MainActivity extends FragmentActivity {

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

As you can see I did not set anything to save state but when I rotate the device, the dialog keep showing up. What I want is to dismiss it. What should I do? Please help me! Thank you!

Upvotes: 0

Views: 404

Answers (2)

MHP
MHP

Reputation: 2731

normally it should disappear,maybe it's because you show your dialog in onCreateView() when device rotate onCreateView() call and your dialog show again.
you can show your dialog by click or anything or use a flag to keep if dialog shown before.

UPDATE:
change dialog width and height in this

        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);

Upvotes: 1

Netero
Netero

Reputation: 3819

when you rotate your device the activty is re-created, so the dialog is shown again, all you need to do is to add prevent that by adding this line of code in your manifest file

android:configChanges="orientation"

see : Android Dialog reopen after rotate device

Upvotes: 0

Related Questions