Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change from one layout view to another and going back?

want to make an Android app that starts with a main layout and when you push a button (called stateButton) that is in this layout the layout changes to a main2 layout containing another button (called boton2), and when you push this one you get back to the first main.

I want to do this in the same activity without creating or starting another one.

Here I show you part of the code:

public class NuevoshActivity extends Activity
implements SensorEventListener, OnClickListener {
    private Button stateButton;
    private Button boton2;

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.main); 
        this.stateButton = (Button) this.findViewById(R.id.boton);
        this.boton2 = (Button) this.findViewById(R.id.boton2);      
        stateButton.setOnClickListener(this);
        boton2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v==stateButton) {
            setContentView(R.layout.main2);             
        }
        else if(v==boton2) {
            setContentView(R.layout.main);
        }
    }
}

The mains only have some images, text views and the buttons.

But I've some troubles. Can't it just be as simple as that or what am I missing or what is wrong?

like image 561
Merol Avatar asked Oct 20 '25 10:10

Merol


1 Answers

When you use findViewById, you are actually trying to find a view inside the layout you specified by the setContentView. So using setContentView again and again might bring problems when you are trying to check for buttons.

Instead of using a setContentView, I would add the 2 layouts for the screen as child's for a view-flipper which only shows one child at a time. And you can specify the index of which child to show. The benefit of using a view flipper is that you can easily specify a 'in' and 'out' animation for the view if you need an animation when you switch between views. This is a lot cleaner method then recalling setContentView again and again.

like image 117
blessanm86 Avatar answered Oct 22 '25 23:10

blessanm86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!