![](/img/trans.png)
[英]How can i make use of views defined in layout XML file as template to create views programmatic way
[英]How can I create Views in xml which I can use for any layout?
例如,當創建ImageView
,我知道可以在Layout
創建它:
示例LinearLayout
:
<LinearLayout...>
<ImageView
android:id="@id/hello_world_id"/>
</LinearLayout>
但是我可以在布局之外定義一個View
,然后將其添加到其他布局中嗎?
我想有一個RelativeLayout
,它可以通過編程方式動態地添加/刪除視圖,以便RelativeLayout
可以在其中不包含任何視圖的情況下開始,然后添加一些,刪除一些等等。是否有任何方法可以做到這一點? 還是僅將這些視圖包含在其他Layout
,然后將Layout
(無論它是什么,包含我的視圖)添加到RelativeLayout
更好嗎?
您要搜索的是LayoutInflator
創建一個xml文件-Buttons.xml
<LinearLayout...> <ImageView android:id="@id/hello_world_id"/>
在您的活動中訪問
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); View itemView = inflater.inflate(R.layout.buttons, null);// this is a layout in your master activity lLayout = (LinearLayout)findViewById(R.id.layout1); lLayout.addView(itemView);
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.