inflated view's id will be repalced by fragment's id after attached?

80 Views Asked by At

I created a fragment inside the activity's layout file. For eg:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:id="@+id/article_fragment"
        android:name="com.user.domain.ArticleFragment"/>
</LinearLayout>

and inflate a view in ArticleFragment::onCreateView function:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    return inflater.inflate(R.layout.article_view, container, false);
}

ariticle_view layout xml looks as below:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/article"
    android:textSize="18sp"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</TextView>

Issue is here: why I can only find the view through fragment's id (R.id.article_fragment) not view's id (R.id.article) after attached, and view instance's id also changed to fragment's id.

Can anybody help to explain the strange behavior?

Document for fragments api has such a description:

The system inserts the View returned by the fragment directly in place of the <fragment> element.

Does that the reason for this issue?

1

There are 1 best solutions below

3
On

You have to find you Fragment's child Views like

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.article_view, container, false);
TextView yourText = v.findViewById(R.id.article);
return v;
}