簡體   English   中英

如何在xml中創建可用於任何布局的視圖?

[英]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

  1. 創建一個xml文件-Buttons.xml

     <LinearLayout...> <ImageView android:id="@id/hello_world_id"/> 

  2. 在您的活動中訪問

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM