Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Android代码实现控件按下显示底色效果

控件设置OnTouchListener,代码如下(控件在xml中需要设置background): btn.setOnTouchListener(new OnTouchListener() {
   
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    Drawable drawable = v.getBackground();
    if (drawable == null)
     return false;
   
    if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.DONUT)// 1.6版本以上使用
    {
     drawable.mutate();
    }
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     drawable.setColorFilter(Color.argb(100, 0, 0, 0), Mode.DST_IN); //此处值可自行调整
     v.setBackgroundDrawable(drawable);
     break;
    case MotionEvent.ACTION_UP:
     drawable.clearColorFilter();
     v.setBackgroundDrawable(drawable);
     break;
    case MotionEvent.ACTION_CANCEL:
     drawable.clearColorFilter();
     v.setBackgroundDrawable(drawable);
     break;
    default:
     break;
    }
    return false;
   }
  });更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-05/101742.htm