简体   繁体   English

如何在xml中创建可用于任何布局的视图?

[英]How can I create Views in xml which I can use for any layout?

When creating an ImageView for example, I know I can create it within a Layout : 例如,当创建ImageView ,我知道可以在Layout创建它:

Example a LinearLayout : 示例LinearLayout

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

But can I define an View outside a layout, and then add it to any other layout? 但是我可以在布局之外定义一个View ,然后将其添加到其他布局中吗?

I want to have a RelativeLayout which adds/removes views programmatically and dynamically, so that the RelativeLayout starts off with no views inside it, then I add some, remove some etc. Would there be any way to do this? 我想有一个RelativeLayout ,它可以通过编程方式动态地添加/删除视图,以便RelativeLayout可以在其中不包含任何视图的情况下开始,然后添加一些,删除一些等等。是否有任何方法可以做到这一点? Or is it better just to have these views already inside some other Layout , and then I add the Layout (whatever it is--containing my view(s)) to my RelativeLayout ? 还是仅将这些视图包含在其他Layout ,然后将Layout (无论它是什么,包含我的视图)添加到RelativeLayout更好吗?

What you are searching for is LayoutInflator 您要搜索的是LayoutInflator

  1. Create a xml file - buttons.xml 创建一个xml文件-Buttons.xml

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

  2. In your activity access it by 在您的活动中访问

 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); 

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用布局XML文件中定义的视图作为模板来以编程方式创建视图 - How can i make use of views defined in layout XML file as template to create views programmatic way 如何在相对布局或任何布局中动态添加视图 - How can I add Views dynamically in a Relative layout or in any Layout 如何访问页脚xml布局内的视图? 安卓系统 - How can I access the views inside of a footer xml layout? Android Android:如何拥有XML布局以及添加到布局中的视图? - Android : How can I have XML layout and the views that I added to my layout? 如何在xml布局中添加两个Scroll视图,以使每个scrollview占据布局高度的一半? - How can I add two Scroll views in a xml layout such that each scrollview take half of the height of the layout? 如何将使用XML布局的视图动态添加到ContentView? - How can I dynamically add Views that use XML Layouts to the ContentView? 如何在线性布局(另一个线性布局的子级)中均匀分布视图? - How can I distribute views in a linear layout (which is a child of another linear layout) evenly? 如何在布局中独立视图 - How Can I independent the views in a layout 如何使用XML完全创建带有选项卡的布局? - How can I create a layout with tabs completely in XML? 如何为不同的活动使用相同的 XML 布局? - How can I use the same XML layout for different activities?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM