Is it possible to have one activity with multiple xml layouts?

Is it possible to create an application that uses a single activity and multiple XML layout files associated with it? I know that you can use setContextView () to open another layout, but when I try to set up any listeners in the activity for other layouts, does it crash? is there a way around this other than using fragments?

+3


source to share


3 answers


It depends on your needs.

You can create a set of layouts that you want to use in your activity. Fill them in and then use them in setContentView (). This solution will work for sure, but you have to be super precise. What for? For each layout change, you must make sure that the links to the links are not null, and that their links still match the displayed location.



Better and easier to create fragments. Let's say you have 4 - 5 separate screens that you want to use in your activities. The activity class will be HUGE and difficult to debug. Using snippets will split your code into 4 separate chunks, making it easier to keep your code clean and nice.

+3


source


Try to inflate layouts in your activity, for example:



public class NavigationView extends LinearLayout {

public NavigationView(Context context) {

    super(context);
    this.init(context);

} 

public void init(Context context) {

    LayoutInflater inflater = LayoutInflater.from(context);
    View v = inflater.inflate(R.layout.nav, this, true);

    Spinner spinner = (Spinner) v.findViewById(R.id.navSpinner);
    if(spinner != null) {

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.nav_sections, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    } 

} 

} 

      

+2


source


If you are using multiple XML layouts in One Activity, the application will not crash.

Give

setContentView(R.layout.XMLLayoutName);

      

It is also possible in Fragments, but Activity is the easiest way to achieve it.

0


source







All Articles