How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1748
旧时难觅i
旧时难觅i 2020-11-22 01:41

Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick tag in a Layout\'s XML:

android:onClick=\"m         


        
18条回答
  •  春和景丽
    2020-11-22 02:05

    I've recently solved this issue without having to add a method to the context Activity or having to implement OnClickListener. I'm not sure if it is a "valid" solution neither, but it works.

    Based on: https://developer.android.com/tools/data-binding/guide.html#binding_events

    It can be done with data bindings: Just add your fragment instance as a variable, then you can link any method with onClick.

    
    
        
            
        
        
    
            
        
    
    

    And the fragment linking code would be...

    public class CustomFragment extends Fragment {
    
        ...
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_person_profile, container, false);
            FragmentCustomBinding binding = DataBindingUtil.bind(view);
            binding.setFragment(this);
            return view;
        }
    
        ...
    
    }
    

提交回复
热议问题