How to set layout dynamically in android

前端 未结 5 1193
無奈伤痛
無奈伤痛 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 20:09

    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:

    someBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.layout2);
    
            someBtn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setContentView(R.layout.layout1);
                }
            });
        }
    });
    
    someBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.layout1);
    
            someBtn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setContentView(R.layout.layout2);
                }
            });
        }
    });
    

    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:

    public void setLayout1(View view) {
        setContentView(R.layout.layout1);
    }
    
    public void setLayout2(View view) {
        setContentView(R.layout.layout2);
    }
    

    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:

    someBtn1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             startActivity(new Intent(this, Activity2.class));
         }
     });
    

    In Activity2.java:

    someBtn2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             finish();
         }
     });
    

提交回复
热议问题