Android 按钮效果的两种实现方法

第一种:
该方法通过onTouch来实现,
[java]  view plain copy
  1. btn3 = (ImageButton) findViewById(R.id.ImageButton03);  
  2. btn3.setOnTouchListener(touchListener3);  
  3. View.OnTouchListener touchListener = new OnTouchListener() {  
  4. @Override  
  5. public boolean onTouch(View v, MotionEvent event) {  
  6. ImageButton imageBtn = (ImageButton) v;  
  7. if(event.getAction() == MotionEvent.ACTION_DOWN){  
  8. //更改为按下时的背景图片  
  9. imageBtn .setImageResource(R.drawable.pressed);  
  10. }else if(event.getAction() == MotionEvent.ACTION_UP){  
  11. //改为抬起时的图片  
  12. imageBtn .setImageResource(R.drawable.released);  
  13. }  
  14. return false;  
  15. }  
  16. };  


第二种:
通过XML来实现
2.用 XML 文件 实现。
[xhtml]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3. <item           
  4. android:state_pressed="false"  
  5. android:drawable="@drawable/button_add" />  
  6. <item           
  7. android:state_pressed="true"  
  8. android:drawable="@drawable/button_add_pressed" />  
  9. <item           
  10. android:state_focused="true"  
  11. android:drawable="@drawable/button_add_pressed" />  
  12. <item           
  13. android:drawable="@drawable/button_add" />  
  14. </selector>  

这个文件放在drawable目录下面。命名为button_add_x.xml
使用的时候
[xhtml]  view plain copy
  1. <ImageButton  
  2. android:id="@+id/ImageButton"  
  3. android:layout_width="wrap_content"  
  4. android:layout_height="wrap_content"  
  5. android:background="#00000000"  
  6. android:src="@drawable/button_add_x"  
  7. >  
  8. </ImageButton>  
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值