【问题标题】:Android fragment is not updatingAndroid片段未更新
【发布时间】:2016-02-23 20:38:52
【问题描述】:

我有一个 TextView 到一个片段中。当我从活动更新文本属性时,组件不会在片段上更新。

TextView amountTag = (TextView) fm.findFragmentByTag("currentFrag").getView().findViewById(R.id.amountTag);
amountTag.setText("another text");

fm 变量是我的FragmentManager

我已经尝试再次分离和附加片段。但它不起作用。

【问题讨论】:

  • 您是否考虑过在 Fragment 类中存储对 TextView 的引用。然后在 Fragment 类中编写一个方法来更新您的文本视图并从您的 Activity 调用它?
  • 您是否要在 Activity 上调用它?创建?或者在Activity的哪个LifeCycle?
  • @Ayzen:我正在尝试在事件“onNewIntent”(读取 NFC 标签)上调用 Activity。
  • @bdavies6086 是的,我做到了。但我有同样的问题。

标签: android android-fragments


【解决方案1】:

检查您是否像这样在片段的onCreateView 中夸大了您的视图:

TextView amountTag;

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_sample, container, false);
    amountTag= (TextView) v.findViewById(R.id.amountTag);
    return v; 
}

如果您有任何问题,请在您的片段中创建 setAmountText

public void setAmountText(String text) {
   amountTag.setText(text); 
}

在你的 Activity 中调用它

((CurrentFragment)fm.findFragmentByTag("currentFrag")).setAmountText("newValue");

希望这会有所帮助!

【讨论】:

  • 同样的问题@g2o。调用 setAmountText 后 TextView 未更新。
【解决方案2】:

我在这里找到了问题的答案:

Handling onNewIntent in Fragment

解决方案是将参数发送到片段,例如:

Bundle bundle = new Bundle();
bundle.putString("amount", "newValue");
fragment.setArguments(bundle);

在片段中:

Bundle bundle = this.getArguments();
if (bundle != null) {
    amountTag.setText(bundle.getString("amount", "defaultValue"));
}

感谢所有提供帮助的人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多