[英]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
Create a xml file - buttons.xml 创建一个xml文件-Buttons.xml
<LinearLayout...> <ImageView android:id="@id/hello_world_id"/>
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.