如何设置上包含布局的onClickListener? [英] How to set an onClickListener on an included layout?
问题描述
我有,我包括在其他几个布局的ImageButton的布局。
I have a layout with an ImageButton that I included in several other layouts.
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时,它的pssed $ P $。 我试过这样:
For this includes I need a onClickListener when it's pressed. I tried this:
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();
}
}
});
不过,这是行不通的。 有谁知道该如何解决?
But it doesn't work. Does anybody know the solution?
推荐答案
替换 findViewById(R.id.includeCallEnd0)
与 findViewById(R。 id.includeCallEnd0).findViewById(R.id.phoneEnd)
,它应该工作
由于要设置在ImageButton的点击监听器,而不是整个布局
because you want to set the click listener on the ImageButton and not the whole layout
使用下面的函数来设置OnClickListener一次:
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);
}
}
}
使用 applyListener(rootView,yourOnClickListener);
这篇关于如何设置上包含布局的onClickListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!