开发者

Insert more stuff in an XML loaded Layout

I'm using setContentView(R.layout.somelayout); to load an XML to my activity.

On this layout, there is a FrameLayout, I want to insert more objects in it dynamically, as an example, more Button Objects.

I haven't found some getCurrentView() method yet... So, how can I get the current Layout from the activity? 开发者_如何学Go


First, assign an id to your FrameLayout in the XML:

<FrameLayout android:id="@+id/MyFrameLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" />

Then, you can access any inflated Views in your Activity after calling setContentView() by using findViewById() in conjunction with the automatically generated R.java:

setContentView(R.layout.somelayout);
FrameLayout layout = (FrameLayout) findViewById(R.id.MyFrameLayout);

findViewById() will search recursively, so regardless where your FrameLayout is, it will be found (as long as there isn't a duplicate id somewhere else in the XML, which you should avoid).

From there, just create the Button dynamically and add it as a child of the FrameLayout:

Button button = new Button(this);
layout.addView(button);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜