Android自定义Button的点击效果

在项目开发中,经常碰到按钮点击,可是如果不添加任何效果,按钮是否点击都是看不出来的。于是我们需要在按钮点击时改变按钮的背景图片或者其颜色。这里给出两种实现方法。

     第一种,是通过在drawable新建selector.xml文件,在里面可以实现自己所需要的点击效果。给出示例代码:

[java] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:drawable="@drawable/button_press" android:state_pressed="true"></item>  
  4.     <item android:drawable="@drawable/button_normal" android:state_focused="false" android:state_pressed="false"></item>  
  5.     <item android:drawable="@drawable/button_normal" android:state_focused="true"></item>  
  6.     <item android:drawable="@drawable/button_normal" android:state_focused="false"></item>  
  7. </selector>  

当按下状态为true,其通过android:state_pressed="true"来定义。相对应的按下去的图片为button_press.当不是按下状态时,即android:state_pressed="false"时,设置其图片为button_normal.

参看如下图片:


接下来只需要在布局文件中设置Button的属性为:

[java] view plaincopy
  1. android:background="@drawable/selector"  

这样就实现了按钮的按下时其会改变背景图片。


第二种实现方法:

[java] view plaincopy
  1. Button button=(Button) this.findViewById(R.id.button);  
  2.        button2.setOnTouchListener(new OnTouchListener() {  
  3.           
  4.         @Override  
  5.         public boolean onTouch(View v, MotionEvent event) {  
  6.             // TODO Auto-generated method stub  
  7.             if(event.getAction()==MotionEvent.ACTION_DOWN){  
  8.                 v.setBackgroundResource(R.drawable.button_press);  
  9.             }else if(event.getAction()==MotionEvent.ACTION_UP){  
  10.                 v.setBackgroundResource(R.drawable.button_nomal);  
  11.             }  
  12.             return false;  
  13.         }  
  14.     });  

这样实现不过代码就比较冗余了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章