[Android] 代码设计中动态设置button的Pressed态图片

来源:互联网 发布:淘宝官方下载 编辑:程序博客网 时间:2024/05/22 11:56

【需求说明】

在代码中动态设置某一个ImageButton的press态图片。对于Button的press态逻辑设计,前面的文章中曾经介绍过 用Selector设置pressed态方式

但是现在有一个新的需求:在代码中动态设置ImageButton的Press态动画。既然可以用selector直接设置button的press态和normal态,那为何还要在代码中动态调整button的

pressed态呢?

这恰好来自于目前所做项目中的一个需求:所有的Activity都继承自一个AppBarActivity,但是对于不同的Activity,对应的AppBar的右边的ImageButton需要有不同的图片显示,

且都具有pressed状态。如果还是以selector方式去做,那么每一个Activity都需要在xml中配置appbar.xml的内容,显然这样没有做到很好的功能复用。而有了代码动态设置Button

的pressed态后,这个问题就很好解决了。只需要在创建各个Activity时传入各自的nomal和press资源ID,在appBar中动态监测imageButton的pressed态,然后设置相应的背景图片即可。


【实现说明】

实现此功能的核心是:ImageButton监听touch事件,当接收到点击按下动作时,设置相应的press资源,点击弹起后,恢复默认的图片资源。

final Button btn = (Button) findViewById(R.id.btn);        btn.setOnTouchListener(new View.OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                if (event.getAction() == MotionEvent.ACTION_DOWN) {                    btn.setBackgroundResource(R.mipmap.btn_status_pressed);                    btn.setTextColor(getResources().getColor(R.color.text_pressed));                } else if (event.getAction() == MotionEvent.ACTION_UP) {                    btn.setBackgroundResource(R.mipmap.btn_status_normal);                    btn.setTextColor(getResources().getColor(R.color.text_normal));                }                return false;            }        });

效果展示


一句话总结:Button响应setOnTouchListener事件,在点击按下动作时,设置pressed态图片,当弹起后,设置normal图片

0 0