Moses Ikomi Moses Ikomi - 4 years ago 146
Android Question

How to switch between layouts in custom dialog fragment (Android)

i'ld like to know how i can switch my dialogs layout file without creating a separate one.

I have a custom dialog fragment i use for connecting to bluetooth devices in my app. It pops up a list of devices and i connect to a device of my choosing.

I have two xml layouts i want to use with this dialog fragment:
- The first one holds the listview for devices i want to connect to
- The other houses and image view

When i connect to a device, i want to switch the layout from the list to the one that houses the imageview. Some where in my code, i have a variable that checks the connection status.

if i'm connected, i switch to the other layout like this:

getDialog().setContentView(R.layout.xml2);


and it works but then when i want to show the dialog again, i get this error.

Attempt to invoke virtual method 'void android.app.Dialog.setContentView(int)' on a null object reference


In my onCreateView method, i'm check my connection state.

if (connected) {

return inflater.inflate(R.layout.xml2, container, false);

} else {

return inflater.inflate(R.layout.xml1, container, false);
}


I know the error has to do with the changing getDialog().setContentView when state changed to connected. I'm thinking about how to revert back to the default view on dismiss so the onCreateView can take effect. If there is another method to doing this, i'ld like to hear about it. Any Ideas?

Thanks in advance...

Answer Source

according to your question, i'ld say you instantiate a variable run at the top:

int run = 0;

when device connects for the firs time, increase run by 1 and switch interface.

In your action method, do:

if (run == 1){
 getDialog().setContentView(R.layout.xml2);
}

so this only runs the first time and wouldn't return null, if dialog is dismissed or cancelled.

To repeat action after first connection, you increase run so as not to cause any conflict

run = 2;

Then in your oncreateview, you can run you code as normal. This save you having to create different dialog fragments.

if (connected) {

    return inflater.inflate(R.layout.xml2, container, false);

 } else {

   return inflater.inflate(R.layout.xml1, container, false);
 }

Hope you find this useful...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download