0

我在活动的布局文件中创建了一个片段。例如:

<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>

ArticleFragment::onCreateView并在函数中膨胀视图:

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

ariticle_view 布局 xml 如下所示:

<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>

问题就在这里: 为什么我在附加后只能通过fragment的id(R.id.article_fragment)而不是view的id(R.id.article)找到视图,并且视图实例的id也变成了fragment的id。

任何人都可以帮助解释这种奇怪的行为吗?

Fragments api的文档有这样的描述:

系统将片段返回的视图直接插入到 <fragment> 元素的位置。

这是这个问题的原因吗?

4

1 回答 1

0

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;
}
于 2014-12-04T09:26:17.710 回答