0

I have an app with a main view and a set of sub-views, defined as XMLs. I load the main view with:

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

When I switch to another view I do:

holaPlayerBtn.setOnClickListener(new OnClickListener(){
@Override

public void onClick(View view)
{   
    setContentView(R.layout.primerareceta);
    };

To go back to the main view I am trying:

@Override

public boolean onKeyDown(int keyCode, KeyEvent event){
    if (keyCode == KeyEvent.KEYCODE_BACK){
        setContentView(R.layout.main);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

But doing this, what I get is the main view repainted, but the buttons that it contains are not functioning any longer.

Do you know why is happening this? How can I go back to the main view with all its button functioning as in the previous time?

Thanks for your help Pedro

Pedro Santangelo
  • 143
  • 2
  • 13

3 Answers3

1

Don't switch layouts like that. I'd recommend using separate activities or you can use the ViewSwitcher.

Michell Bak
  • 13,182
  • 11
  • 64
  • 121
1

When you call setContentView you are replacing what is on the screen. This effectively removes all listeners and views you had in place before. To do it you might want to but your original initialization code inside of a function that your can call inside of onCreate as well as when the back button is pressed.

This does seem like a lot of work when what you are asking for sounds like the standard application flow. It would be easier to have a main activity and instead of changing views you should be changing between activities using startActivity. This will also give you the behavior you desire with the back button without you having to write any code to handle it.

Bobbake4
  • 24,509
  • 9
  • 59
  • 94
1

I don't think you're allowed to call setContentView more than once. And either way you definitely shouldn't.

ViewSwitcher javadoc

first example

second example

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
  • that is a good option. It will make the back button function how it seems like you want it to automatically – FoamyGuy Oct 21 '11 at 13:29