How to handle button clicks using the XML onClick within Fragments

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

    In my use case, I have 50 odd ImageViews I needed to hook into a single onClick method. My solution is to loop over the views inside the fragment and set the same onclick listener on each:

        final View.OnClickListener imageOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chosenImage = ((ImageButton)v).getDrawable();
            }
        };
    
        ViewGroup root = (ViewGroup) getView().findViewById(R.id.imagesParentView);
        int childViewCount = root.getChildCount();
        for (int i=0; i < childViewCount; i++){
            View image = root.getChildAt(i);
            if (image instanceof ImageButton) {
                ((ImageButton)image).setOnClickListener(imageOnClickListener);
            }
        }
    

提交回复
热议问题