【问题标题】:Reloading fragment, Edittext's text not cleared重新加载片段,Edittext 的文本未清除
【发布时间】:2017-11-18 17:56:08
【问题描述】:

在我的片段中有很多微调器和编辑文本,提交按钮用于保存数据,重置按钮用于重置所有元素(编辑文本和微调器)。我使用以下代码重置所有控件

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();

但它不会清除edittext。所有微调器都被重置,但 editext 的文本保持原样

【问题讨论】:

  • 我没有手动清除文本。我想通过重新加载片段来清除所有控件
  • 最好的方法是手动清除它们。重新加载片段很昂贵。

标签: android android-fragments android-edittext reset fragmentmanager


【解决方案1】:

detach().detach() 在支持库更新 25.1.0(可能更早)后不起作用。此解决方案在更新后运行良好:

注意:

使用 runOnUiThread() 来使用 commitNowAllowingStateLoss

    getSupportFragmentManager()
    .beginTransaction()
    .detach(oldFragment)
    .commitNowAllowingStateLoss();

   getSupportFragmentManager()
    .beginTransaction()
    .attach(oldFragment)
    .commitAllowingStateLoss();

【讨论】:

    【解决方案2】:

    试试这个:

     FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
     ft.remove(this).replace(R.id.container, YourFragment.newInstance());;
     ft.commit();
    

    性能说明:如果您只是为了重置值而替换片段,那么手动重置值会更好,因为与手动重置值相比,替换整个片段会产生大量额外开销。

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 2014-07-29
      • 1970-01-01
      • 2022-10-12
      相关资源
      最近更新 更多