How to set an onClickListener on an included layout?

后端 未结 3 1844
刺人心
刺人心 2021-01-02 11:52

I have a layout with an ImageButton that I included in several other layouts.

ImageButton Layout:

call_cancelled.xml

相关标签:
3条回答
  • 2021-01-02 11:59

    Try to set your clickListener on callEndLayout (LinearLayaout)

    0 讨论(0)
  • 2021-01-02 12:11

    You could have done

    LinearLayout endcall0 = (LinearLayout) findViewById(R.id.includeCallEnd0); 
    

    and then simply

    ImageButton imgBtn = (ImageButton) endcall0.findViewById(R.id. phoneEnd); 
    imgBtn.setOnClickListener(this);
    
    0 讨论(0)
  • 2021-01-02 12:19

    Replace findViewById(R.id.includeCallEnd0) with findViewById(R.id.includeCallEnd0).findViewById(R.id.phoneEnd) and it should work

    because you want to set the click listener on the ImageButton and not the whole layout


    Use the following function to set the OnClickListener once:

    private static void applyListener(View child, OnClickListener listener) {
        if (child == null)
            return;
    
        if (child instanceof ViewGroup) {
            applyListener((ViewGroup) child, listener);
        }
        else if (child != null) {
            if(child.getId() == R.id.phoneEnd) {
                child.setOnClickListener(listener);
            }
        }
    }
    
    private static void applyListener(ViewGroup parent, OnClickListener listener) {
        for (int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                applyListener((ViewGroup) child, listener);
            } else {
                applyListener(child, listener);
            }
        }
    }
    

    Use applyListener(rootView, yourOnClickListener);

    0 讨论(0)
提交回复
热议问题