简体   繁体   中英

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

Is it possible to create an app that uses one activity and several layout xml files associated with it? I know you can use setContextView() to open another layout but when I try to set up any listeners in the activity for the other layouts it crashes? is there a way around this other than using fragments?

It depends what are your needs.

You can create set of layouts which you want to use in your activity. Inflate them and then use them in setContentView(). This solution for sure will work, but you will have to be super precise. Why? For each layout change, you have to be sure that view references are not null and their references still correspond to displayed layout.

Its better and easier to create fragments. Lets assume you will have 4 - 5 separate screens which you want to use in activity. Activity class will be HUGE and hard to debug. Using fragments will split the code into 4 separate fragments, which will be easier to keep clean and nice code.

Try inflating layouts into 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);
    } 

} 

} 

If you use Multiple XML layout in One Activity, App will not crash.

Give

setContentView(R.layout.XMLLayoutName);

In Fragments also its possible, but Activity is easiest way to achieve it.

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