我們在使用ViewStub的時候,一般ViewStub都是特定條件出發inflate的。這種觸發條件有多個的時候(或者有多處ViewStub的inflate 代碼時)我們往往需要判斷ViewStub之前有沒有inflate過。
經過參考網上的文檔,總結找出了兩種方法:
1.ViewStub被inflate后就不會再布局中存在。所以每次在inflate的時候重新findViewById去頁面中尋找一下ViewStub,如果返回值不為null則ViewStub沒有被inflate過。
// 每次在inflate之前都調用一遍findViewById
ViewStub viewStub= (ViewStub) findViewById(R.id.viewstub); if(viewStub!=null){ viewStub.inflate(); }
2.利用ViewStub的parent來判斷。當ViewStub被inflate后,getParent返回值是null
//初始化,不必每次都調用 ViewStub viewStub= (ViewStub) findViewById(R.id.viewstub); .... if(viewStub.getParent() !=null){ viewStub.inflate(); }
推薦使用第二種方法。