This article is followed by the example of the include tag above, address http://blog.csdn.net/jason0539/article/details/26131831
The viewstub control is used in the layout of the previous article. Now let's talk about its functions and usage.
"
ViewStub is an invisible View with a size of 0. The best use is to implement delayed loading of the View to avoid wasting resources and load the View only when needed.
"
It should be noted that after loading the view, viewstub itself will be replaced by the newly loaded view.
After reading the code, I can understand it.
Acitivity_main.xml
InflatedId is the id of the newly loaded view. To obtain this view, use this inflatedId. The original id has been replaced.
Layout is the layout to be loaded. The Code is as follows:
Pic_view.xml
There is only one picture in it
MainActivity. java
Public class MainActivity extends Activity {private ViewStub pic_sub; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); pic_sub = (ViewStub) findViewById (R. id. pic_stub); new Timer (). schedule (new TimerTask () {@ Overridepublic void run () {handler. sendEmptyMessage (1) ;}}, 1000); // delay 1 second, then load} Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {View pic_view = pic_sub.inflate (); // ① // pic_sub.setVisibility (View. VISIBLE); // ② ImageView iv_pic = (ImageView) pic_view.findViewById (R. id. iv_pic); iv_pic.setImageResource (R. drawable. pic); View view = findViewById (R. id. pic_stub); // view = findViewById (R. id. pic_view_id_after_inflate); // ④ };};}
① When inflate () is called, The loaded view replaces viewstub and returns its own view object. This makes it unnecessary for the application to execute findViewById () to obtain the reference of the loaded view.
② The sentence is not required. If setvisibility is used, the order of the two sentences cannot be reversed; otherwise, an error is returned.
Java. lang. IllegalStateException: ViewStub must have a non-null ViewGroup viewParent, because viewstub cannot repeatedly inflate, only once inflate, setVisibility will indirectly call inflate
① Obtain the loaded pic_view, so that the application does not need to execute findViewById () to obtain the reference of the loaded view. If you want to obtain it by yourself, use inflateid.
③ Here, the view will be null, because viewstub is replaced, and the id of pic_stub does not exist.
④ Use inflateid to get the loaded view.
Author: jason0539
Weibo: http://weibo.com/2553717707
Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)