首页 > 解决方案 > 如何更改片段中的 TextView 值

问题描述

我正在尝试更改 Fragment 中的 TextView 值,但它没有清除旧值。

价值与旧价值重叠。

在此处输入图像描述

来自片段的代码 -

public class MainFragment extends Fragment {

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

    t1 = view.findViewById(R.id.textview1);
    t1.setText(s1);

    return view;
}
}

来自活动的代码 -

public static String s1;
@Override
public void onOptionClicked(int position, Object objectClicked) {
    // Set the toolbar title
    setTitle(mTitles.get(position));

    // Set the right options selected
    mMenuAdapter.setViewSelected(position, true);
    s1 = mTitles.get(position);
    // Navigate to the right fragment
    switch (position) {
        default:
            goToFragment(new MainFragment(), false);
            break;
    }
    // Close the drawer
    mViewHolder.mDuoDrawerLayout.closeDrawer();
}

片段 xml 文件 -

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

<LinearLayout xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

</LinearLayout>

尝试使用以下代码但无法正常工作....

public void setText(String text){
        TextView textView = (TextView) getView().findViewById(R.id.detailsText);
        textView.setText(textview1);
    }

请帮助....提前谢谢...!

标签: androidandroid-studioandroid-fragmentstextview

解决方案


正如 Ranjan 所说,这不是一个好习惯,为什么不在MainFragment mf = new MainFragment();onCreate() 内部创建并在该方法中使用它。这样,您将只有一个实例。我不使用这样的片段,所以我对您的代码没有好主意。


推荐阅读