How to use View Stub in android

前端 未结 3 585
野趣味
野趣味 2020-12-13 02:07

I want to use ViewStub in android, so please help me. I have created

ViewStub stub = new ViewStub;
View inflated = stub.inflate(); 

How to

3条回答
  •  时光说笑
    2020-12-13 02:23

    Simply a ViewStub is used to increase efficiency of rendering layout. By using ViewStub, manually views can be created but not added to view hierarchy. At the runtime, can be easily inflated, while ViewStub is inflated, the content of the viewstub will be replaced the defined layout in the viewstub.

    activity_main.xml we defined viewstub but not created first.enter image description here

    Simple example gives better understanding,

    
        

    At runtime, when we inflate, the content will be replaced with the layout defined in the viewstub.

    public class MainActivity extends Activity {
    
        Button b1 = null;
        Button b2 = null;
    
        ViewStub stub = null;
        TextView tx = null;
    
        int counter = 0;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            b1 = (Button) findViewById(R.id.btn1);
            b2 = (Button) findViewById(R.id.btn2);
            b1.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (stub == null) {     
                        stub = (ViewStub) findViewById(R.id.stub_import);
                        View inflated = stub.inflate();
                        tx = (TextView) inflated.findViewById(R.id.text1);
                        tx.setText("thanks a lot my friend..");
                    } 
    
                }
            });
    
            b2.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    if (stub != null) {
                        stub.setVisibility(View.GONE);
                    }
    
                }
            });
    
        }
    

    enter image description here

    So, Lets look at again the view hierarchy,

    enter image description here

    when we inflate the viewstub, it will be removed from the view hierarchy.

提交回复
热议问题