【问题标题】:Repopulating values in Android Fragment onResume在 Android Fragment onResume 中重新填充值
【发布时间】:2012-01-03 21:27:40
【问题描述】:

我有一个带有 TextView 的 Fragment(A),使用 setText() 方法设置了值“XXXX”。我将 Fragment(A) 替换为 Fragment(B),然后再次将 B 替换为 A。

当我这样做时,Fragment(A) TextView 中的值 XXXX 消失了。我尝试在 onStart 和 onResume 方法中调用 TextView.setText 方法 - 结果相同。当我调试代码时,我可以从字面上看到正在使用的 setText 方法和值 XXXX 在那里。我在 LogCat 上打印出来了,它也在那里,但我在屏幕上看不到任何值。

我尝试用谷歌搜索,但没有得到答案。我会很感激任何指示。

代码

public void onResume() { 
  super.onResume(); 
  String dData = readFileFromSDCard(); 
  String dArray[] = dData.split(";"); 
  txtName = (TextView) getActivity().findViewById(R.id.txtName); 
  txtName.setText("first name")
}

【问题讨论】:

  • 请您发布一些代码。
  • 我的 onResume 上有这个:code public void onResume() { txtName = (TextView) getActivity().findViewById(R.id.txtName); txtName.setText("XXXX");这就是我替换的方式: DI di = new DI(); fragmentTransaction.replace(R.id.topFrame, di); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();这是我的 xml 用户界面:codecode

标签: java android replace fragment


【解决方案1】:

对于片段,您无法使用getActivity().findViewById(R.id.txtName); 获得布局,您应该这样做。当您将片段 B 替换回 A 时也会调用此方法。

这段代码当然需要站在你的 Fragment 类中。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.your_layout, container, false);        
    String driverData = readFileFromSDCard(); 
    String driverArray[] = driverData.split(";"); 
    txtName = (TextView) view.findViewById(R.id.txtName); 
    txtName.setText("Andrew");

}

【讨论】:

  • 谢谢。 getView() 而不是 getActivity() 做到了。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
相关资源
最近更新 更多