android - 如何更改片段中的 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);
}
请帮助....提前谢谢...!
解决方案
正如 Ranjan 所说,这不是一个好习惯,为什么不在MainFragment mf = new MainFragment();
onCreate() 内部创建并在该方法中使用它。这样,您将只有一个实例。我不使用这样的片段,所以我对您的代码没有好主意。
推荐阅读
- c# - 确保 appSettings 键中没有拼写错误
- java - 未找到 Java ANT build.xml 错误驱动程序
- spfx - 如何使用 SPFx 从 SharePoint 中的所有页面中删除侧导航和顶部标题区域
- javascript - 取消 JavaScript 承诺
- javascript - 如何将 Angular 应用程序用于另一个 Angular 应用程序的子路由?
- .net - 从本机应用程序访问 Azure Key Vault
- ios - 在 iOS 12 中生成 QR/Aztec 代码的替代方法
- c# - ILMerge targetplatform 到 4.6.2 问题
- python - Libtorrent:在magnet_link uri中添加多个跟踪器
- python - ValueError:未知标签类型:'连续