Android 无法修改片段数据

Android 无法修改片段数据,android,android-fragments,Android,Android Fragments,我在view pager中使用了以下片段: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/win

我在view pager中使用了以下片段:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/window_background"
android:id="@+id/font"
tools:context="com.cuentos.lib.cuentosmusicales.Libro">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:gravity="center"
    android:id="@+id/titleBook"
    android:textSize="25sp"
    android:textColor="#2211CC"
    android:text="@string/hello_blank_fragment" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/titleBook"
    android:id="@+id/textBook"
    android:textSize="15sp"
    android:textColor="#44BB11"
    android:text="@string/hello_blank_fragment" />
</RelativeLayout>

因此,我检测到我无法更改数据,因为没有更改,所以我如何在片段中实例化textview?

在重写片段时尝试设置文本
onActivityCreated
onResume
方法。

首先,您要将视图膨胀两次。onCreateView的第一行有一个视图,它是修改TextView的视图,但是在创建并返回另一个的return语句中,您并没有返回您修改的视图,而是返回一个新的视图,因此UI中显示的视图是未修改的视图

此外,您在错误的生命周期阶段调用findViewById。请注意,onCreateView返回将出现在片段中的视图。以这种方式检索像您的TextViews这样的视图组件是不可能的,因为视图本身还不存在

修改视图组件的正确方法是在onViewCreated中:

@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
    title = (TextView) view.findViewById(R.id.titleBook);
    text1 = (TextView) view.findViewById(R.id.textBook);

    title.setText("hi friends");
    text1.setText(text);
}
对不起,我没有设置“”但我已经更新了代码,请再次检查
@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
    title = (TextView) view.findViewById(R.id.titleBook);
    text1 = (TextView) view.findViewById(R.id.textBook);

    title.setText("hi friends");
    text1.setText(text);
}