- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试使用 fragment 来构建我的第一个合适的 Android 应用程序。我有一个主要的 xml。它由两个垂直 fragment 组成,顶部 fragment 仅由两个 TextView 组成。其中第一个包含静态文本,第二个包含一个我最终将从 SQL 动态获取的值。
如果我把它放在我的 MainActivity.java 中,它就会愉快地更新我第一个 fragment 中 TextView 的值:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
我有两个 fragment XML 和一个 java 来支持每个 fragment ,所以我想将此字段的设置放入支持 fragment 的 Java 而不是用于 MainActivity 的 java。
当我把它放在 fragment 中时,它看起来像这样:-
public class FragmentMainTop extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// -- inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentmt, container,false);
// Set the Text to try this out
TextView t = (TextView)findViewById(R.id.viewItem);
t.setText("Text to Display");
}
但如果我这样做,我会在 TextView 行上收到错误:
“对于 FragmentMainTop 类型未定义方法 findViewById(int)”
那么为什么它不知道这个方法呢?我有 ctl/shift/o 所以我知道我有所有正确的进口。我不想最终将所有代码都放在 MainActivity 中,因为如果我想在另一个 Activity 中使用 Fragment,我将不得不重复所有代码。
最佳答案
您需要将膨胀的 fragment 布局分配给一个变量,以便您可以访问其 findViewById()
方法。然后在完成更新小部件后将其返回。
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
// -- inflate the layout for this fragment
View myInflatedView = inflater.inflate(R.layout.fragmentmt, container,false);
// Set the Text to try this out
TextView t = (TextView) myInflatedView.findViewById(R.id.viewItem);
t.setText("Text to Display");
return myInflatedView;
}
通常,当您在 Activity
中调用 findViewById()
时,您将调用 Activity.findViewById()
。在 Fragment
类中尝试相同的调用将失败,因为没有这样的 Fragment.findViewById()
方法。因此,您必须将 View.findViewById()
与您的膨胀 View 一起使用,以获取对您的小部件的引用。
关于安卓 : How do I update my textView in a Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15322237/
我是一名优秀的程序员,十分优秀!