kevinjqy 2014-10-20 04:48 采纳率: 0%
浏览 1270

将基于activity的代码移植到基于fragment的页面中

private void initView() {

    expandTabView = (ExpandTabView) findViewById(R.id.expandtab_view);

    viewLeft = new LeftFilterView(this, FilterDataSource.createPriceFilterItems());

    viewMiddle = new MiddleFilterView(this);

    viewRight = new RightFilterView(this, FilterDataSource.createSortFilterItems());

}

上方代码要是移植到fragment页面中需要修改什么?
我改成了这样,但是运行时调用view的时候出现了空指针
private void initView() {

    expandTabView = (ExpandTabView) getActivity().findViewById(R.id.expandtab_view);

    viewLeft = new LeftFilterView(getActivity(), FilterDataSource.createPriceFilterItems());

    viewMiddle = new MiddleFilterView(getActivity());

    viewRight = new RightFilterView(getActivity(), FilterDataSource.createSortFilterItems());

}
  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-02 22:21
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在Fragment页面中,你需要使用getActivity()方法来获取当前活动。这将会返回一个FragmentActivity对象。然后你可以像之前一样使用findViewById方法来查找控件。

    以下是修改后的代码:

    private void initView() {
        expandTabView = (ExpandTabView) getActivity().findViewById(R.id.expandtab_view);
    
        viewLeft = new LeftFilterView(getActivity(), FilterDataSource.createPriceFilterItems());
    
        viewMiddle = new MiddleFilterView(getActivity());
    
        viewRight = new RightFilterView(getActivity(), FilterDataSource.createSortFilterItems());
    }
    

    注意:在Fragment页面中,你可能需要先创建一个新的FragmentManager实例,并将其传递给你的ExpandTabView和所有其他视图组件。例如:

    FragmentManager fragmentManager = getSupportFragmentManager();
    

    然后,在初始化视图时,可以像之前一样使用findViewByRid方法。

    评论

报告相同问题?