如何更改片段中的 TextView 值 [英] How to change TextView Value in fragment

查看:43
本文介绍了如何更改片段中的 TextView 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to change TextView value in Fragment but it not clearing old value.

值与旧值重叠.

来自片段的代码 -

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>

尝试使用下面的代码但不起作用....

Tried by using below code but not working....

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

请帮忙.... 提前致谢...!

Please help.... Thanks in Advance...!

推荐答案

如果你在你的 goToFragment() 代码中使用了 .add,那么你应该用 .add 替换代码>.replace

If you are using .add in your goToFragment() code, then you should replace with .replace

fragmentTransaction.add(R.id.container,
             currentFragment).commit()

fragmentTransaction.replace(R.id.fragment_container,
             currentFragment).commit()

这篇关于如何更改片段中的 TextView 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆