简体   繁体   中英

two different layouts for one activity

是否可以为同一活动中的不同案例设置两种不同的布局,或者我是否必须使用intent来调用具有不同布局的另一个activity

Yes its possible. You can use as many layouts as possible for a single activity but obviously not simultaneously. You can use something like:

if (Case_A)
  setContentView(R.layout.layout1);

else if (Case_B)
  setContentView(R.layout.layout2);

and so on...

Yes this is also possible with switch case

I already tried this code....

switch (condition) {
        case 1:  
    setContentView(R.layout.layout1);
                 break;
        case 2:  
    setContentView(R.layout.layout2);
                 break;
        case 3:  
    setContentView(R.layout.layout3);
                 break;

        default: 
    setContentView(R.layout.main);
                 break;
    }

I suggest using Fragments

It will be helpful if you can explain more to find other solutions if your not ok with fragments

Edit

Use android support libraries for supporting lower OS versions

Edit2

if you want to use two xml you can combine two xml into one and use it

<include layout="@layout/YOURXMLNAME1" />
<include layout="@layout/YOURXMLNAME2" />

this is also useful while using layout again in many cases

You can refer to this link

Using two layout xml file for one Activity

Here is best solution for you ViewFlipper .
ViewFlipper is a Simple ViewAnimator that will animate between two or more views that have been added to it. Only one child is shown at a time. If requested, can automatically flip between each child at a regular interval. Here is good example of viewflipper.
You can also look at this .
EDIT: - One StackoverFlow answer for you

There are a number of ways to go about this. The other answers include at least two approaches - using setContentView depending on the case and using fragments. There is one more I'd like to talk about. Say for instance, you include two layouts

<include
android:id = "@+id/layout1"
layout = .../>

<include
android:id = "@+id/layout2"
layout = ...
android:visibility = "gone"/>

In your java code, you can then hide or show your layouts depending on the use case. For instance, setting the content view to show the layout above shows layout1. When user clicks next button, you can then get a reference to layout1 and set it's visibility to gone and layout2's visibility to visible.

LinearLayout layout1 = findViewById(R.id.layout1);
LinearLayout layout2 = findViewById(R.id.layout2);

buttonNext.setOnClickListener(new View.OnClickListener()
{ 
layout1.setVisibility(View.GONE);
layout2.setVisibility(View.VISIBLE);
});

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