【发布时间】:2013-10-13 02:59:49
【问题描述】:
我正在尝试编写一个片段,该片段具有在 TextView 中设置某些内容的方法。所以我有以下片段:
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
// setText("set it to something");
return view;
}
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
}
这很好用。它显示了文本视图。我现在想以编程方式编辑 textview 中的文本。我想我首先要从片段中编辑它。所以我有了应该能够做到的方法。当我现在取消注释setText("set it to something");时,它给了我一个InflateException: Error inflating class fragment.,我不知道为什么。
有人知道我该如何解决这个问题吗?
【问题讨论】:
-
在 onResume 中调用你的方法
-
@Waqas - 谢谢。确实像一个魅力!其他人还建议在 onCreateView 中执行其他方法。哪一种是最好/正确的方法;在 onCreateView 中还是在 onResume 中?
-
在
onResume()中执行此操作将导致每次暂停和恢复片段时都会调用此方法,这很糟糕,因为有时片段只是暂停和恢复(当显示对话框时)在这种情况下它无缘无故重新设置文本不是一个好主意。我建议您将此电话转至onViewCreated()或onActivityCreated()。 -
@M-WaJeEh 我知道我的建议是一个快速的解决方案。从技术上讲,它应该在 onActivityAttached 中调用 :)
标签: java android xml android-fragments