繁体   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