如何在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前面添加 插入的那个布局,它就能识别是哪一个布局了。



原创粉丝点击