【问题标题】:How to inflate View on my layout?如何在我的布局上膨胀视图?
【发布时间】:2012-02-21 04:38:39
【问题描述】:

如何在布局上膨胀视图,我在布局上的所有 ui 元素都应该可见。 我正在尝试这条线,但它不起作用我无法看到我的背景图片、按钮和其他图片。

MyView view1=new MyView(this);

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

请帮忙..提前致谢。

【问题讨论】:

  • 为什么这个演员表是“(MyView)”..?

标签: android android-view android-linearlayout


【解决方案1】:

对于你正在做的事情,使用

setContentView(R.layout.main);

inflating 后没有得到你的视图的原因是你需要在当前视图的某个地方添加那个视图。目前,您的膨胀视图是孤立的。

【讨论】:

  • 你的仪式,顺便说一句,我在当前视图中添加了我的视图,但我没有得到。实际上,我有一个类扩展了 View,我在视图上画了一条线。在活动布局 xml 中,我添加了不可见的背景 imageViews 和按钮。但我能够完美地画线。我想你得到了我的问题..
【解决方案2】:

这通常有效...

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

<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 

希望对你有帮助..

【讨论】:

  • @ntc.. Myview 是我的视图类。
  • Myview 扩展了 View 类。我可以在哪里画线。我已将视图设置为 contentview,但它不起作用
  • @Hema .. 你为什么要这样做.. 在 xml 中创建一行,然后将其设置为内容视图... 不像你正在做的那样复杂的东西..
【解决方案3】:

终于成功了。

getWindow().addContentView(view1,
                new ViewGroup.LayoutParams(
                         ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多