How to use data-binding with Fragment

后端 未结 14 1030
不思量自难忘°
不思量自难忘° 2020-11-29 16:48

I\'m trying to follow data-binding example from official google doc https://developer.android.com/tools/data-binding/guide.html

except that I\'m trying to apply data

相关标签:
14条回答
  • 2020-11-29 17:31

    Even the other answers may work well, but I want tell best approach.

    Use Binding class's inflate as recommended in Android Documentation.

    One option is to inflate by DataBindingUtil but when only you don't know have generated binding class.

    --You have auto generated binding class, use that class instead of using DataBindingUtil.

    In Java

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        HomeFragmentBinding binding = HomeFragmentBinding.inflate(inflater, container, false);
        //set binding variables here
        return binding.getRoot();
    }
    

    In Kotlin

    lateinit var binding: HomeFragmentBinding 
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = HomeFragmentBinding.inflate(inflater, container, false)
        return binding.root
    }
    

    In DataBindingUtil class documentation you can see.

    inflate

    T inflate (LayoutInflater inflater, 
                    int layoutId, 
                    ViewGroup parent, 
                    boolean attachToParent)
    

    Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

    If your layout biniding class is not generated @See this answer.

    0 讨论(0)
  • 2020-11-29 17:31

    A complete example in data binding Fragments

    FragmentMyProgramsBinding is binding class generated for res/layout/fragment_my_programs

    public class MyPrograms extends Fragment {
        FragmentMyProgramsBinding fragmentMyProgramsBinding;
    
        public MyPrograms() {
            // Required empty public constructor
        }
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
        FragmentMyProgramsBinding    fragmentMyProgramsBinding = DataBindingUtil.inflate(inflater, R
                    .layout.fragment_my_programs, container, false);
            return fragmentMyProgramsBinding.getRoot();
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题