How to set layout dynamically in android

前端 未结 5 1198
無奈伤痛
無奈伤痛 2020-12-02 19:08

Well, Suppose there is an Activity called MainActivity and there are two layouts called layout1 and layout2 both have few

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 19:59

    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.

    public class MainActivity extends Activity {
    
        private final View.OnClickListener setLayout1Listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               setContentView(R.layout.layout2);
               ((Button)findViewById(R.id.Btn2Id)).setOnClickListener(setLayout2Listener);
               //do other stuff
            }
        };
    
        private final View.OnClickListener setLayout2Listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               setContentView(R.layout.layout1);
               ((Button)findViewById(R.id.Btn1Id)).setOnClickListener(setLayout1Listener);
               //do other stuff
            }
        };
    
    
    
        @Override
        public void onCreate(final Bundle savedInstance) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout1);
            ((Button)findViewById(R.id.Btn1Id)).setOnClickListener(setLayout1Listener);
            //do other stuff
        }
    }
    

提交回复
热议问题