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

时间:2013-10-07 13:31:47

标签: android onclicklistener

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

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>

我的收录:

  <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" />

对于这包括我按下时需要一个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();
            }
        }
     });

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

3 个答案:

答案 0 :(得分:2)

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);
        }
    }
}

使用applyListener(rootView, yourOnClickListener);

答案 1 :(得分:1)

你可以做到

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

然后简单地

ImageButton imgBtn = (ImageButton) endcall0.findViewById(R.id. phoneEnd); 
imgBtn.setOnClickListener(this);

答案 2 :(得分:0)

尝试在callEndLayout(LinearLayout)上设置onclickListener

相关问题