简体   繁体   中英

how to stop background activity from running when an alert dialog is running in android

I have an alertdialog with two edit texts and when a user tries to input text into one of the edit texts, a new instance of the background activity seems to be created. How do I stop that from happening?

@Override
public boolean onSearchRequested() {
    showDialog(DIALOG_SEARCH_ID);

    return false;
}

protected Dialog onCreateDialog(int id) {
    switch(id) {
    case DIALOG_SEARCH_ID:
        LayoutInflater factory = LayoutInflater.from(this);
        final View searchView = factory.inflate(R.layout.searchbar2, null);
        AlertDialog ad = new AlertDialog.Builder(TravelBite.this)
            .setView(searchView)
            .create();
        Window win = ad.getWindow();
        win.setGravity(48);
        return ad;
    }
    return null;
}

Straight from the google's Android developer documentation:

...When a configuration change occurs at runtime, the activity is shut down and restarted by default...

I assume this is what's happening; the background activity is being restarted due to a device configuration change (such as screen orientation, input modes, screen size, etc.).

In your manifest file, declare that both your background activity and your AlertDialog activity handle a configuration change, ie:

<activity android:name=".MyActivity"
          android:configChanges="locale|navigation|orientation"
          android:label="@string/app_name">

You can change the attributes for android:configChanges depending on your situation.

Take a look at the Android documentation and see which attributes you need: http://developer.android.com/guide/topics/manifest/activity-element.html#config

Dialogs are created asynchronously. As in, when the engine hits

AlertDialog ad = new AlertDialog.Builder(TravelBite.this)
            .setView(searchView)
            .create();

it generates a call to create that, and keeps on going straight to Window win = ad.getWindow(); .

You'll need to handle it via flags and/or more logic inside the dialog's onClick handlers.

So, when you egt the code built for handling the dialog's edittexts and buttons, paste it here :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM