【问题标题】:Android Custom Component doesn't show anything after inflate充气后Android自定义组件不显示任何内容
【发布时间】:2011-10-03 10:39:54
【问题描述】:

尝试创建一个从 XML 文件 (box.xml) 获取其布局的自定义组件。我已经阅读了几个教程,但似乎无法显示任何内容。下面是我的自定义组件的构造函数,代码执行时没有错误。

public class MyView extends LinearLayout {
    //Constructor required for inflation from resource file
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);        
        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=layoutInflater.inflate (R.layout.box, this);                        
        Log.d("CONSTRUCTOR 2", "TESTER");        
    }
}

我将组件添加到布局中:

<com.mysample.MyView android:layout_width="50dp" android:layout_height="38dp" android:background="#FF000000" />

黑色块确实出现在屏幕上,但与我膨胀它的 xml 文件的布局无关。

【问题讨论】:

    标签: android components android-inflate


    【解决方案1】:

    您需要将创建的视图添加到线性布局中。

    公共MyView(上下文上下文,AttributeSet attrs){ 超级(上下文,属性); View view = inflate(context, R.layout.box, null); 添加视图(视图); }

    这应该可行。顺便看看你的Logcat中的Log吗?

    这里是 box.xml(示例一)。您需要使用 MyView 的完全限定类名,无论您想在哪里使用它。

    线性布局>

    检查这个sample project here

    【讨论】:

    • 如果我将它添加到底部的构造函数中,我会得到错误:this.addView(view);错误:java.lang.IllegalStateException:指定的孩子已经有一个父母。
    • 查看 view=layoutInflater.inflate (R.layout.box, null);
    • 执行但不显示任何内容: View view=layoutInflater.inflate(R.layout.tile, null); this.addView(view);
    • 这对我有用。你也可以显示你的盒子xml吗?您可以直接使用视图类的 inflate 方法,而不是创建 LayoutInflater 的实例
    • 我不能在这里发布代码,因为我只能发布 550 个字符。还有其他方法可以向您展示代码吗?非常感谢您尝试帮助我解决此问题。
    猜你喜欢
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多