如何在我的布局上充气视图?

时间:2012-02-21 04:38:39

标签: android android-view android-linearlayout

如何在布局上对视图进行充气,其中布局中的所有ui元素都应该是可见的。 我正在尝试这一行,但它无法正常工作,我无法看到我的背景图像,按钮和其他图像。

  

MyView view1 = new MyView(this);

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 view1= (MyView) inflater.inflate(R.layout.main, null);

请帮助..提前致谢。

3 个答案:

答案 0 :(得分:2)

对于您正在做的事情,请使用

setContentView(R.layout.main);

充气后无法获取视图的原因是您需要在当前视图中添加该视图。目前,您的虚增视图已成为孤儿。

答案 1 :(得分:1)

这通常有用......

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View view1= inflater.inflate(R.layout.main, null);

 LayoutInflater inflater = LayoutInflater.from(getApplicationContext);
View view1= inflater.inflate(R.layout.main, null);

然后将此视图添加到contentView。

<强>更新

假设您需要在main.xml中绘制一条线,请允许我给您这个建议。通过扩展View类而不是在运行时绘制线,在xml中创建一个像这样的视图

<View android:layout_width = "fill_parent"
      android:layout_height = "2dp"  //assuming you want line of 2dp thickness
      android:background= "@android:color/black"/> // define your desired color here 
希望它有所帮助..

答案 2 :(得分:0)

这终于奏效了。

getWindow().addContentView(view1,
                new ViewGroup.LayoutParams(
                         ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
相关问题