0

我想my_layout.xml从代码中自定义我的布局定义(在文件中声明)。

不幸的是,我可以使用findViewById()函数来查找特定视图(在my_layout.xml文件中定义)并仅在调用 setContentView(R.layout.my_layout).

但是,如果我想在调用之前先自定义布局setContentView()怎么办?如何在调用之前访问特定视图setContentView()

4

4 回答 4

0
LayoutInflater myInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout)myInflater.inflate(R.layout.first_layout, null); 
setContentView(layout);
于 2013-08-02T16:01:22.060 回答
0
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout myLayout = (RelativeLayout)inflater.inflate(R.layout.my_layout, null); 

现在您可以使用 R.layout.my_layout 中定义的视图/资源并添加到您的自定义布局中。

于 2013-08-02T15:33:39.077 回答
0

使用 LayoutInflater 是解决方案:

LayoutInflater li=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout v= (LinearLayout)li.inflate(R.layout.activity_main, null);
    Button b=v.findViewById(R.id.button);
    setContentView(v);
于 2013-08-02T15:34:37.537 回答
0

onCreateView只是为了这个目的。只需在您的活动或片段中覆盖它,您就可以在其中自定义您的视图。

于 2014-10-30T20:49:05.433 回答