How to handle button clicks using the XML onClick within Fragments

前端 未结 18 1517
旧时难觅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:03

    I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well.

    public class StartFragment extends Fragment implements OnClickListener{
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_start, container, false);
    
            Button b = (Button) v.findViewById(R.id.StartButton);
            b.setOnClickListener(this);
            return v;
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.StartButton:
    
                ...
    
                break;
            }
        }
    }
    

提交回复
热议问题