布局没有在android自定义组件中膨胀

时间:2012-10-29 13:51:56

标签: android custom-component android-custom-view layout-inflater

我在自定义视图中获取了一个空指针异常(它是从LinearLayout派生的),因为它找不到它的子视图。这是代码:

public class MyView extends LinearLayout
{
    public MyView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public MyView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    private TextView mText;

    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();
        mText = (TextView) findViewById(R.id.text);

        if (isInEditMode())
        {
            mText.setText("Some example text.");
        }
    }
}

这是布局(my_view.xml):

<?xml version="1.0" encoding="utf-8"?>
<com.example.views.MyView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:ellipsize="end"
        android:maxLines="4"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="Some text" />

</com.example.views.MyView>

以下是我将它放在XML文件中的方式:

    <com.example.views.MyView
        android:id="@+id/my_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

但是当我尝试在布局编辑器中预览时,我会在mText.setText(...)上获得NPE,因为getViewById()会返回null

发生了什么事?

澄清

我希望这个工作的原因是,如果我这样做

MyView v = (MyView)inflater.inflate(R.layout.my_view);
((TextView)v.findViewById(R.id.text)).setText("Foo");
一切正常。这不是布局inflater在通过布局文件时所做的事情吗?在任何情况下,我如何正确处理这两种情况(没有获得毫无意义的嵌套视图)?

1 个答案:

答案 0 :(得分:4)

在您的XML文件中,您尝试使用自定义视图类(com.example.views.MyView),同时尝试在其中添加TextView。这是不可能的。

以下是您需要更改的内容:

您必须在代码中填充XML文件:

public MyView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    LayoutInflater.from(context).inflate(R.layout.<your_layout>.xml, this);
}

并修改XML布局文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<TextView
    android:id="@+id/text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:gravity="center"
    android:ellipsize="end"
    android:maxLines="4"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:text="Some text" />

</LinearLayout>