我怎样才能实现"喜欢"按钮?

时间:2017-04-19 22:05:05

标签: android button onclicklistener

我需要实现一个类似的按钮我所寻找的逻辑是,当你点击时,颜色会改变按钮,当你再次点击时,你又有了相同的颜色

我用过这个

  // LIKE
            viewHolder.shakaLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(viewHolder.shakaLike.isChecked()) {
                        Drawable myLike = getResources().getDrawable(R.drawable.nuevo_arrow_verde);
                        viewHolder.shakaLike.setBackgroundDrawable(myLike);


                        Drawable myLikeM = getResources().getDrawable(R.drawable.middleblack);
                        viewHolder.middleFinger.setBackgroundDrawable(myLikeM);

                        onLikeClick(model.getPostId());
                    }else if (!viewHolder.shakaLike.isChecked()){
                        Drawable m = getResources().getDrawable(R.drawable.nuevo_arrow_blanco);
                        viewHolder.shakaLike.setBackgroundDrawable(m);
                    }

                }
            });

但不起作用 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您需要确保您的方法反转您在if检查中使用的布尔值。所以,如果它还没有被喜欢(喜欢=假),那么设置喜欢等于true,因为现在喜欢它,并将箭头设置为绿色背景。

viewHolder.shakaLike.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(!liked) {
           liked = true; //because it wasn't liked(default state at start), but it was clicked to make it liked
           viewHolder.middleFinger.setBackgroundDrawable(green);
        } else if (liked){
            liked = false; //because it was liked and was clicked to unlike
            viewHolder.shakaLike.setBackgroundDrawable(white);
        }
    }
});

答案 1 :(得分:0)

尝试类似

的内容
Drawable green = getResources().getDrawable(R.drawable.nuevo_arrow_verde);
Drawable white = getResources().getDrawable(R.drawable.nuevo_arrow_blanco);

boolean liked = false;

viewHolder.shakaLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clicked = !clicked;
                if(liked) {
                   viewHolder.middleFinger.setBackgroundDrawable(green);
                } else if (!viewHolder.shakaLike.isChecked()){
                    viewHolder.shakaLike.setBackgroundDrawable(white);
                }


            }
        });