Well, Suppose there is an Activity called MainActivity and there are two layouts called layout1 and layout2 both have few buttons. By default MainActivity layout is layout1 like following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
Now what I did actually is by clicking a button in layout1 the second layout is set like following:
someBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setContentView(R.layout.layout2);
}
});
There are another button in layout2 to return back to layout1 like following:
someBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setContentView(R.layout.layout1);
}
});
Problem is when I returned back to layout1 then OnClickListener of someBtn1 is not working. It seems I need to set OnClickListener again for someBtn1 of layout1. How I can write code to make them work perfectly with best practices ?
When you are seting layout2, you should also set up OnClickListener to someBtn1 and vice versa, I'd suggest something like this. But as in prevoius answer, in general you should avoid mixing layouts in such manner.
At the time you callback layout1, data must be set again.
You could merge both layouts in one and then use ViewFlipper to switch between them.
One way of doing this is loading both views in
onCreate(...)
, and then switching between them by making the one you don't want invisible. Something like the following:The best practice is to use fragments instead of change the content view.
In your code, setContentView with layouts recreate (inflate) all your views every time, so the call setContentView(R.layout.layout1) in someBtn2 click listener will create a new button without the associated listener.
If you don't want to use fragments you can do this:
The listeners will be:
If you just want to play around with your current code, a solution for your problem is that the listeners must be redeclared when the layout changes, as follows:
An alternative to avoid declaring the listeners twice is to declare two methods to handle the layout changes and use the
onClick
property of the button in each of the layouts, for example:In
layout1.xml
:In
layout2.xml
:However, if you want to follow best practices, the best practice is not to mix layouts in the same activity, but instead declare two different activities (each one with its own layout) and call one activity or the other depending on the button that was clicked. Suppose that you are in Activity1 and want to call Activity2, then go back to Activity1:
In
Activity1.java
:In
Activity2.java
: