Das Layout wird in der benutzerdefinierten Android-Komponente nicht aufgeblasen

In meiner benutzerdefinierten Ansicht wird eine Nullzeigerausnahme angezeigt (die von a abgeleitet ist)LinearLayout), weil es seine untergeordneten Ansichten nicht finden kann. Hier ist der Code:

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.");
        }
    }
}

Hier ist das Layout (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>

Und so füge ich es in die XML-Datei ein:

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

Wenn ich jedoch versuche, eine Vorschau im Layout-Editor anzuzeigen, wird eine NPE angezeigtmText.setText(...) dagetViewById() kehrt zurücknull.

Was ist los?

Klärung

Ich erwarte, dass dies funktioniert, wenn ich es tue

MyView v = (MyView)inflater.inflate(R.layout.my_view);
((TextView)v.findViewById(R.id.text)).setText("Foo");

alles funktioniert gut Ist es nicht das, was der Layout Inflater macht, wenn er eine Layoutdatei durchläuft? Wie kann ich in jedem Fall beide Situationen richtig handhaben (ohne sinnlose verschachtelte Ansichten zu erhalten)?

Antworten auf die Frage(1)

Ihre Antwort auf die Frage