I want to use ViewStub in android, so please help me. I have created
ViewStub stub = new ViewStub;
View inflated = stub.inflate();
How to
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.
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);
}
}
});
}
So, Lets look at again the view hierarchy,
when we inflate the viewstub, it will be removed from the view hierarchy.