我有一个like
按钮RecyclerView
,我想要的是当用户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 答案,所以我修改了我的代码如下,但单击按钮时仍然没有任何反应。
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();
}
}
});
有人请指出我遗漏了什么,我想要的是在第一次点击时以编程方式更改按钮颜色,并在下次点击时改回默认值(避免来自同一用户的多次点击)。
嗨尝试这个希望这可以帮助你...
在 XML 中
<Button
android:id="@+id/btnClick"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:text="click"/>
在适配器类中
boolean click = true;
holder.btnClick.setTag(position);
holder.btnClick.setId(position);
holder.btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (click) {
holder.btnClick.setBackgroundColor(Color.RED);
click = false;
} else {
holder.btnClick.setBackgroundColor(Color.WHITE);
click = true;
}
notifyDataSetChanged();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句