如何在Fragment中使用findViewById
来源:互联网 发布:如何添加usb打印端口 编辑:程序博客网 时间:2024/05/16 01:21
findViewById方法却只能被用在Activity类中,如果想在fragment中使用,
需要在findViewById前面 添加getView();
下面是一段代码,
public class SquareFragment extends Fragment { private TextView sq; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View square = inflater.inflate(R.layout.square_layout, container, false); sq =getView().findViewById(R.id.square); sq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity ma = (MainActivity) getActivity(); ma.setTabSelection(2); } }); return square; }}
这样用getView()前面没有问题,但是运行会发现空指针异常,原因呢是在使用了onCreateView创建视图, inflater插入的布局,用getView()引用,不是识别是哪一个布局
所以就报了空指针,
正确的写法如下
public class SquareFragment extends Fragment { private TextView sq; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View square = inflater.inflate(R.layout.square_layout, container, false); sq = square.findViewById(R.id.square); sq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity ma = (MainActivity) getActivity(); ma.setTabSelection(2); } }); return square; }}
在findViewById前面添加 插入的那个布局,它就能识别是哪一个布局了。
阅读全文
0 0
- 如何在Fragment中使用findViewById呢?
- 如何在Fragment中使用findViewById
- Fragment中为什么不能使用findViewById???
- 在Fragment中加载布局后使用findViewById出现空指针错误
- 在 fragment 里面调用 findViewById
- 在 fragment 里面调用 findViewById
- 在 fragment 里面调用 findViewById
- fragment 中加载UI布局和使用findviewbyid
- 在非Activity类中使用findViewbyid
- 在Fragment中如何使用Toolbar
- MPAndroidChart如何在Fragment中使用
- 如何在Fragment中使用phonegap的CordovaWebView
- 如何在Fragment中使用phonegap的CordovaWebView
- Android: 如何在Fragment中使用上下文Context
- [Android] 如何在 Fragment 中使用 runOnUiThread() 方法
- Android: 如何在Fragment中使用上下文Context
- AndroidStudio中使用Kotlin--findViewById
- 在Fragment中使用GestureDetector
- zlog使用手册
- 机器学习、数据挖掘相关资源链接(持续补充...)
- Android源码解析之运行时ART简要介绍和学习计划
- 2线性分类器基本原理-2.2线性分类器之SVM和折叶损失(Hinge Loss)
- RNN训练方法介绍-BPTT
- 如何在Fragment中使用findViewById
- Spark性能优化指南——基础篇 (转自美团)
- 设计模式——外观模式
- MSP430G2553 1602显示字符
- HttpWebRequest HttpClient
- LibZXing 二维码
- linux 安装LAMP环境(centos7.4)
- 系统自带导航栏的注意事项
- 使用javacc实现语法生成器(基于miniC语法)