如何在包含的布局上设置 onClickListener?

sil*_*aut 8 android onclicklistener

我有一个包含在其他几个布局中的 ImageButton 布局。

图像按钮布局:

call_cancelled.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:id="@+id/callEndLayout"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:height="70dip"
    android:orientation="horizontal"
    android:paddingBottom="5dp"
    android:paddingTop="5dp" >

    <ImageButton
        android:id="@+id/phoneEnd"
        android:layout_width="63dp"
        android:layout_height="63dp"
        android:paddingBottom="7dp"
        android:background="@drawable/phone_cancelled"  />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我的包括:

  <include
   android:id="@+id/includeCallEnd0"
   android:layout_width="70dp"
   android:layout_height="70dp"
   android:layout_alignBottom="@+id/include"
   android:layout_alignParentRight="true"
   layout="@layout/call_cancelled" />
Run Code Online (Sandbox Code Playgroud)

对于这包括我在按下时需要一个 onClickListener 。 我试过这个:

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

 endcall0.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent callIntent = new Intent(Intent.ACTION_CALL_BUTTON);
            startActivity(callIntent);

            int id = viewFlipper.getDisplayedChild();

            if (id == 0) {
                hideSoftKeyboard();
            }
        }
     });
Run Code Online (Sandbox Code Playgroud)

但它不起作用。有人知道解决方案吗?

She*_*tib 7

替换findViewById(R.id.includeCallEnd0)findViewById(R.id.includeCallEnd0).findViewById(R.id.phoneEnd)它应该可以工作

因为您想在 ImageButton 上设置单击侦听器而不是整个布局


使用以下函数设置 OnClickListener 一次:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

applyListener(rootView, yourOnClickListener);