Ankush
Ankush

Reputation: 801

two different layouts for one activity

Is it possible to have two different layouts for different cases in the same activity or do I have to use intent to call another activity with a different layout

Upvotes: 21

Views: 66187

Answers (5)

Samuel Agbede
Samuel Agbede

Reputation: 380

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);
});

Upvotes: 4

Arvind Kanjariya
Arvind Kanjariya

Reputation: 2097

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;
    }

Upvotes: 12

Sandip Armal Patil
Sandip Armal Patil

Reputation: 5895

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

Upvotes: 1

Just Variable
Just Variable

Reputation: 877

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

Upvotes: 4

Ankush
Ankush

Reputation: 6927

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...

Upvotes: 36

Related Questions