无法修改片段数据

时间:2015-08-10 16:41:04

标签: android android-fragments

我在视图寻呼机中有以下片段:

<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值
public class Libro extends Fragment {
String titleLibro;
String text;
TextView title, text1;

public Libro() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_libro, container, false);

    title = (TextView) view.findViewById(R.id.titleBook);
    text1 = (TextView) view.findViewById(R.id.textBook);

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

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_libro, container, false);
   }
}

所以,我发现我无法更改数据因为没有变化,所以我怎样才能在片段中实现textview?

2 个答案:

答案 0 :(得分:0)

尝试在覆盖碎片onActivityCreatedonResume方法时设置文字。

答案 1 :(得分:0)

首先,你要两次夸大你的观点。 onCreateView的第一行有一个,你修改了TextViews,但是在你创建并返回另一个的return语句中,你没有返回你修改过的那个,而是返回一个新的,所以视图将在UI中显示的内容未经修改。

此外,您在错误的生命周期阶段调用findViewById。请注意,onCreateView返回将在片段中显示的视图。由于视图本身尚不存在,因此无法以这种方式检索像您的TextView那样的视图组件。

修改视图组件的正确方法是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);
}