ViewBinding - how to get binding for included layouts?

后端 未结 4 877
北恋
北恋 2020-12-08 04:15

While working with ViewBinding I come across few not documented cases.

First: How to get binding for included generic view layout parts, main binding see only items

4条回答
  •  隐瞒了意图╮
    2020-12-08 04:34

    Your first question, that is working with an included layout using ViewBinding can be solved so easily.

    Here is a sample main_fragment.xml file

    
    
    
        
    
        
    
    
    

    And MainFragment.java can be like this

    public class MeaningFragment extends Fragment {
    
        private MainFragmentBinding binding;
        private ToolbarBinding toolbarBinding;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
            binding = MainFragmentBinding.inflate(inflater, container, false);
            toolbarBinding = binding.toolbar;
    
            return binding.getRoot();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
            toolbarBinding = null;
            binding = null;
        }
    }
    

    Now, you have two bindings. one of them is the default and the next one is from the included layout.

提交回复
热议问题