2012-04-12 52 views

回答

20

setonclicklistner为您布局文件的主要布局....

像.... main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/mainlayout"> 
<!- Your other view-> 
</Relativelayout> 

,并设置点击mainlayout听者...

RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout); 
rlayout.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 

    } 

}); 
+1

什么是OnClickListener的完整类名? android.view.View.OnClickListener? – tgkprog 2016-04-23 08:30:37

+1

android.view.View.OnTouchListener可用于通用x,y触摸监听 – tgkprog 2016-04-23 08:51:02

1

给你的主布局一个ID,然后

LinearLayout root = (LinearLayout) findViewById(R.id.main_layout); 
root.setOnClickListener(new OnClickListener() { 
    public void onClick() 
    { 

    } 
}); 
0

也许你可以添加一个侦听布局实例,得到了布局

RelativeLayout l = (RelativeLayout)findViewById(R.id.mylayout); 
l.setOnClickListener(click); 
0

您还可以直接设置回调从根布局onClick XML属性:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:onClick"myMethod"> 
<!- Your other view-> 
</Relativelayout> 

而且在您的活动:

public void myMethod(View pView) { 
    //XXX do something 
} 

少臃肿的代码这种方式:)

1

我认为最简单的方法是在覆盖onUserInteractionActivity

要知道,当用户集中开/关EditText S和Spinners(可能是其他小工具也是如此)它不会着火。但每次用户触摸屏幕或按下按钮时都会触发。

但是这样做不需要在您的布局中创建监听器,也不需要编写额外的方法来处理这些监听器,所以我相信这是获得您想要的最麻烦的方式。

相关问题