Alone_mat_Jenin
AfterYoung
2021-04-02 12:34
采纳率: 50%
浏览 36

fragment如何不通过onViewCreated方法从布局文件中引入view

  @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (BarStatusHeightUtil.checkDeviceHasNavigationBar(getActivity())){
            BarStatusHeightUtil.hideBottomUIMenu(getActivity());
        }
        if(rootView == null){
            rootView = inflater.inflate(getContentViewId(),container,false);
            initViews();
            initData();
            addListener();
        }else{
            ViewGroup parent =(ViewGroup)rootView.getParent();
            if (parent != null){
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

这是Basefragment

 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

这是Alarmfragment

 @Override
    public void initViews() {

        toolbar = view.findViewById(R.id.title_toolbar);
        webView = view.findViewById(R.id.wv_warn);
        
        initToolbars();
        LoadWeb();
        String erro = MyApplication.getCache().getAsString("error");
        if (erro != null){
//            warnJs(erro);
        }
    }

这是initViews

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • knight1996
    knight康康 2021-04-02 14:28
    已采纳

    把Basefragment 的onCreateView方法中的 initViews、initData、addListener 方法 移到 Basefragment的 onViewCreated中调用

     @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
                initViews(view);
                initData();
                addListener();
     
        }
    
    
    //initView 添加一个参数View
    abstract void initViews(View view);
    
    

    在子类的initViews就可以通过view.findViewById 了

     @Override
        public void initViews(View view) {
     
            toolbar = view.findViewById(R.id.title_toolbar);
            webView = view.findViewById(R.id.wv_warn);
     
        }
    点赞 评论
  • Alone_mat_Jenin
    AfterYoung 2021-04-02 13:43

    这是报错信息

    点赞 评论

相关推荐