Android FrameLayout内部片段中的setText()
因此,我的应用程序中有一个框架布局,其中包含多个片段。 我做了一个底部导航,一切都很好,但我需要更新其中一个文本视图,无论我在网上挖多远,我都无法让它工作 我在onCreate中所做的是:(它不会停留在onCreate中,这只是暂时看看它是否有效) 我的片段是:Android FrameLayout内部片段中的setText(),android,android-fragments,Android,Android Fragments,因此,我的应用程序中有一个框架布局,其中包含多个片段。 我做了一个底部导航,一切都很好,但我需要更新其中一个文本视图,无论我在网上挖多远,我都无法让它工作 我在onCreate中所做的是:(它不会停留在onCreate中,这只是暂时看看它是否有效) 我的片段是: private static final String TAG = "HOME"; TextView moneyMonth; @Nullable @Override public Vi
private static final String TAG = "HOME";
TextView moneyMonth;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home,container,false);
Log.d(TAG, "onCreateView: fml ");
moneyMonth = v.findViewById(R.id.moneyThisMonth);
return v;
}
void updateMoneyMonth(String text){
moneyMonth.setText(text);
}
我不知道哪里不对,因为我看过的很多教程都是我自己做的。
我还看到很多人使用id而不是标签,我如何将id添加到片段中?当它在FrameLayout中时
很抱歉,如果这看起来有点愚蠢,或者只是解决方案非常简单,对片段来说非常陌生。您需要将数据传递给要在Textview上显示的片段
Fragment fr = new HomeFragment();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
fr.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.container,fr).commit();
在片段的onCreateView方法中,从Bundle中获取字符串并设置为TextView,如下所示-
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home,container,false);
String value = getArguments().getString("YourKey");
moneyMonth = v.findViewById(R.id.moneyThisMonth);
moneyMonth.setText(value);
return v;
}
你是从你的父活动fragment中调用你的片段吗?你的意思是我有我的片段存在,然后我从主活动中生成片段是吗?如果是这样的话,那么它现在就可以工作了,不过,我的应用程序使用计时器,每秒更新3个TextView。它们会更新onCreate()方法,但之后,我会更新args.putString(“三个键之一”,“一个值”);在从计时器调用的许多函数中。最后,我有一个函数,它执行
fr.setArguments(args);getSupportFragmentManager().beginTransaction().replace(R.id.container,fr.commit()代码>由于某些原因,此操作不会更新片段。如何使用args中的新值每秒更新片段中的TextView?另外:Bundle和fr设置在oncreate之外。如果它对您有效,您可以接受它作为答案。
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home,container,false);
String value = getArguments().getString("YourKey");
moneyMonth = v.findViewById(R.id.moneyThisMonth);
moneyMonth.setText(value);
return v;
}