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

Tim*_*mmm 5 android custom-component android-custom-view layout-inflater

我在自定义视图(从a派生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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是布局(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>
Run Code Online (Sandbox Code Playgroud)

这是我把它放在XML文件中的方式:

    <com.example.views.MyView
        android:id="@+id/my_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)

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

这是怎么回事?

澄清

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

MyView v = (MyView)inflater.inflate(R.layout.my_view);
((TextView)v.findViewById(R.id.text)).setText("Foo");
Run Code Online (Sandbox Code Playgroud)

一切正常.这不是布局inflater在通过布局文件时所做的事情吗?在任何情况下,我如何正确处理这两种情况(没有获得毫无意义的嵌套视图)?

sda*_*bet 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);
}
Run Code Online (Sandbox Code Playgroud)

并像这样修改 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>
Run Code Online (Sandbox Code Playgroud)