Java – how to dynamically set the layout in Android
Then, suppose there is an activity called mainactivity. There are two layouts, layout1 and layout2, with few buttons The default layout of mainactivity is layout1, as shown below:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout1);
Now I actually click a button in layout1. The second layout is set as follows:
someBtn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setContentView(R.layout.layout2); } });
There is also a button in layout2 to return to layout1, as shown below:
someBtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setContentView(R.layout.layout1); } });
The problem is that when I return to layout1, somebtn1's onclicklistener does not work It seems that I need to set onclicklistener again for somebtn1 of layout1 How do I write code to make them use best practices perfectly?
Solution
The best practice is to use fragments instead of changing the content view
In your code, setcontentview and layout will recreate (expand) all your views every time, so some btn2 click the setcontentview (r.layout. Layout1) call in the listener to create a new button without an associated listener
If you don't want to use clips, you can do this:
private View view1,view2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); view1 = getLayoutInflater().inflate(R.layout.layout1,null); view2 = getLayoutInflater().inflate(R.layout.layout2,null); setContentView(view1);
The audience will be:
someBtn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setContentView(view2); } }); someBtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setContentView(view1); } });