《代码里的世界》 —UI篇
用文字札记描绘自己 android学习之路
转载请保留出处 by Qiao
http://blog.csdn.net/qiaoidea/article/details/45850641
【导航】
- 单行文本水平触摸滑动效果 通过EditText实现TextView单行长文本水平滑动效果
- 多行文本折叠展开 自定义布局View实现多行文本折叠和展开
1.概述
说起空间动态、微博的点赞效果,网上也是很泛滥,各种实现与效果一大堆。而详细实现的部分,讲述的也是参差不齐,另一方面估计也有很多大侠也不屑一顾,觉得完全没必要单独开篇来写和讲解吧。毕竟,也就是两个view和一些简单的动画效果罢了。
单若是只讲这些,我自然也是不愿花这番功夫的。虽然自己很菜,可也不甘于太菜。所以偶尔看到些好东西,可以延伸学写下,我还是很情愿拿出来用用,顺带秀一秀逼格什么的。
不扯太多,先说说今天实现点赞效果用到的自以为不错的两个点:
- Checkable 用来扩展View实现选中状态切换
AndroidViewAnimations 基于nineoldandroids封装的android动画简易类库。究竟有多简单呢,就像这样
AnimHelper.with(new PulseAnimator()).duration(1000).playOn(imageView);
作用: 在imageView上使用PulseAnimator这个动画效果,播放一秒。当然是从实现角度来看这个库啦,如果仅仅是使用,google/百度一大堆啦。
结合前两篇富文本折叠展开,加上我们的点赞view 做出的demo整合效果图:
2.从实现看门道
其实从效果看无非就是点击切换图片,并添加一些简单动画效果而已,确实没什么难度。这里是因为引入了两个不错的新内容,使用下,权当新手尝鲜。
2.1 Checkable接口实现CheckedImageView
系统本身提供了android.widget.Checkable这样一个接口,方便我们继承实现View的选中和取消的状态。看下这个类:
public interface Checkable {
/**
* 设置view的选中状态
*/
void setChecked(boolean checked);
/**
* 当前view是否被选中
*/
boolean isChecked();
/**
*改变view的选中状态到相反的状态
*/
void toggle();
}
通常这个接口用来帮助我们快速实现view的可选效果,增加了选中和取消两种状态和切换方法。另外为了方便View在状态改变时候快速地变看到效果(更背景或图片),我们可以直接通过selector控制图片,而其本身并不会自动改变drawable状态,因此这里还有必要重写drawableStateChanged
方法。我们先以定义一个通用的CheckedImageView为例:
public class CheckedImageView extends ImageView implements Checkable{
protected boolean isChecked;//选中状态
protected OnCheckedChangeListener onCheckedChangeListener;//状态改变事件监听
public static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckedImageView(Context context) {
super(context);
initialize();
}
public CheckedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
private void initialize() {
isChecked = false;
}
@Override
public boolean isChecked() {
return isChecked;
}
@Override
public void setChecked(boolean isChecked) {
if (this.isChecked != isChecked) {
this.isChecked = isChecked;
refreshDrawableState();
if (onCheckedChangeListener != null) {
onCheckedChangeListener.onCheckedChanged(this, isChecked);
}
}
}
@Override
public void toggle() {
//改变状态
setChecked(!isChecked);
}
//初始DrawableState时候为它添加一个CHECKED_STATE,ImageView本身是没有这个状态的
@Override
public int[] onCreateDrawableState(int extraSpace) {
int[] states = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDr