[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
- [Android] 代码设计中动态设置button的Pressed态图片
- EXTjs4 动态设置 button pressed 状态切换
- Android给Button设置drawableRigh 在代码中动态改变
- Android中控件的事件——xml设置对应效果state_[pressed,checked,selected,focused]
- Android在代码中动态设置文本的图片的显示
- activity中设置button的图片
- Android代码中动态设置图片的大小(自动缩放),位置
- 如何在代码中动态为TextView/Button设置drawableRight
- Android 代码里动态设置TextView/Button等的文字颜色Seletor
- TextView,Button的DrawableLeft,,Right 使用代码动态的设置
- android代码中动态设置布局中控件的属性
- android代码中动态设置布局中控件的属性
- Android中简单的Button设计
- android代码中动态调整图片的位置
- Android根据Button状态(normal,focused,pressed)显示不同背景图片
- Android根据Button状态(normal,focused,pressed)显示不同背景图片
- Android根据Button状态(normal,focused,pressed)显示不同背景图片
- Android根据Button状态(normal,focused,pressed)显示不同背景图片
- hdu 2899 Strange fuction
- Struts2 回顾与复习
- firefox查看http请求
- 学习笔记(三)——关于Service的那些事
- 基于ARP的局域网IP劫持——C语言实现
- [Android] 代码设计中动态设置button的Pressed态图片
- 【Linux系统编程】进程间通信--有名管道
- 第四章:Linear Models for Classification
- 信号及信号处理
- 171.View the Exhibit and examine the command used to create the ZONEDATA table.
- django 学习网址
- 【Linux系统编程】进程间通信--消息队列
- HDU_2055解题报告(JAVA)
- Java EE 笔记三