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?


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.



Try to inflate layouts in your activity, for example:

public class NavigationView extends LinearLayout {

public NavigationView(Context 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(;
    if(spinner != null) {

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.nav_sections, android.R.layout.simple_spinner_item);






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




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



All Articles