public class ViewStubDemoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewstub_demo_activity);
if ((((int) (Math.random() * 100)) & 0x01) == 0) {
// to show text
// all you have to do is inflate the ViewStub for textview
ViewStub stub = (ViewStub) findViewById(R.id.viewstub_demo_text);
stub.inflate(); //让布局显示出来
TextView text = (TextView) findViewById(R.id.viewstub_demo_textview);
text.setText("The tree of liberty must be refreshed from time to time" +
" with the blood of patroits and tyrants! Freedom is nothing but " +
"a chance to be better!");
} else {
// to show image
// all you have to do is inflate the ViewStub for imageview
ViewStub stub = (ViewStub) findViewById(R.id.viewstub_demo_image);
stub.inflate();
ImageView image = (ImageView) findViewById(R.id.viewstub_demo_imageview);
image.setImageResource(R.drawable.happy_running_dog);
}
}
}
使用的时候的注意事项:
1. 某些布局属性要加在ViewStub而不是实际的布局上面,才会起作用,比如上面用的android:layout_margin*系列属性,如果加在TextView上面,则不会起作用,需要放在它的ViewStub上面才会起作用。而ViewStub的属性在inflate()后会都传给相应的布局。