android 中checkBox的onclik方法实现

来源:互联网 发布:cad数控冲床编程 编辑:程序博客网 时间:2024/06/03 14:48

对勾选声音进行设置


1.进入声音设置,勾选“选择操作音”; 

2.勾选文件或文件夹时观察是否有选择操作音; 
此时应该会对应的有选择操作音的,但为什么无选择操作音? 
<CheckBox 
   android:id="@+id/checkbox" 
   android:layout_width="wrap_content"    
   android:layout_height="wrap_content" 
   android:focusable="false"> 
</CheckBox>  

    原来SoundManager对于CheckBox的check事件不感冒,只对click事件产生作用,而对于CheckBox有setOnCheckedChangeListener的API,但是没有setOnClickListener,那CheckBox如何响应onClick事件呢?有一个属性可以在XML中可以配置。 
CheckBox的API描述是这样的: 
1.When the user selects a checkbox, the CheckBox object receives an on-click event. 

To define the click event handler for a checkbox, add the android:onClick attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method. 

2.The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must: 

•Be public 
•Return void 
•Define a View as its only parameter (this will be the View that was clicked) 

故此时需要修改配置文件: 
<CheckBox 
   android:id="@+id/CheckBox" 
   android:layout_width="wrap_content"    
   android:layout_height="wrap_content" 
   android:focusable="false" 
   android:onClick="sound"> 
</CheckBox>  

然后在加载该控件对应的配置文件的Activity中实现该函数,这里直接为空函数即可,注意这个函数必须是public权限,返回值为void,指定唯一参数View。 
public void sound(View view){ 

} 
OK,大功告成!此时勾选就可以听到清脆的勾选声了。 

   但是在实际的项目中,由于编译选择的方式可能为user模式,此时user模式对编译进行了优化,该sound函数只是一个空函数,在编译检查的时候发现其未被调用,就直接被优化掉了,在sound函数加一行Log编译不同的user和eng版本,查看是否有Log输出,就可以知道了,那优化掉了,这里点击checkbox此时就会报错,因为找不到该函数。 
   解决方法,在编译.mk文件中添加下列语句将优化禁用掉,再编译任何模式的版本就不会有问题了。 
   LOCAL_PROGUARD_ENABLED :=disabled
0 0