我的RecyclerView
中有一个like
按钮,我想要的是当用户第一次点击like
按钮时,按钮背景颜色将变为red
颜色,当同一用户按下like
按钮时,按钮将会改变回到默认颜色即white
。单击时如何更改按钮的颜色,并在下次单击时恢复为默认颜色?
我检查了几个SO问题,但仍然没有得到我想要的。到目前为止,我的解决方案如下,没有产生任何错误,但点击按钮时,什么也没有发生。
likeButton =(Button) view.findViewById(R.id.likeButton);
//here for user like the post
holder.likeButton.setOnClickListener(new View.OnClickListener() {
boolean clicked = true;
@Override
public void onClick(View v) {
if(!clicked){
holder.likeButton.setBackgroundColor(Color.RED);
clicked = true;
//here i will update the database
}else{
holder.likeButton.setBackgroundColor(Color.WHITE);
clicked = false;
//here i will update the database
}
}
});
我检查这个SO answer太多,所以我修改我的代码如下,但是单击按钮时仍然没有任何反应。
holder.likeButton.setBackgroundColor(Color.WHITE);
holder.likeButton.setOnClickListener(new View.OnClickListener() {
ValueAnimator buttonColorAnim = null;
@Override
public void onClick(View v) {
if(buttonColorAnim != null){
buttonColorAnim.reverse();
buttonColorAnim = null;
//here i will update the database
}else{
final Button button = (Button) v;//here is the line I dont undestand
buttonColorAnim = ValueAnimator.ofObject(new ArgbEvaluator(), Color.RED, Color.WHITE);
buttonColorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
// set the background color
button.setBackgroundColor((Integer) animator.getAnimatedValue());
}
//here i will update the database
});
buttonColorAnim.start();
}
}
});
有人请指出什么我失踪,我要的是改变按钮的颜色是编程时点击第1次,并改回默认为下一个点击(这避免这样多来自同一个用户) 。
你的第一个例子似乎是正确的,但是,你的'clicked'变量赋值TRUE; ,这意味着'!clicked'总是假的,你的代码永远不会被执行。 – MatusMak
所以我应该为第一个例子分配false? @MatusMak – ken
downvote的原因? – ken