首页 > 解决方案 > 根据以前的颜色更改按钮背景颜色

问题描述

我有一个非常简单的问题

考虑我正在使用getText()Method在线检索字符串值

现在根据字符串的值,我将按钮背景设置为红色和蓝色。

如果字符串值为红色,则按钮背景为红色,如果为蓝色,则为蓝色。

现在,如果我实现onClicklistener同一个按钮,我想更改它的背景颜色。如果是红色,则将其更改为蓝色,如果是蓝色,则只要用户按下键,就将其更改为红色。

 mSolved = (Button) itemView.findViewById(R.id.book_solved); 
 mSolved.setText(g.getColorvalue()); 

 if("Blue".equals(holder.mSolved.getText())){
  mSolved.setBackgroundColor(BLUE);
 }
 if("Red".equals(holder.mSolved.getText())){
  .mSolved.setBackgroundColor(RED);
 }

mSolved.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     if(Background color is already BLue)
 {
     change to Red
 }
 else
 {
    Change to Blue
 }
}

标签: javaandroidonclickandroid-button

解决方案


尝试使用 FLAG 变量。类似的东西。

mSolved = (Button) itemView.findViewById(R.id.book_solved); 
mSolved.setText(g.getColorvalue()); 

boolean IS_BLUE = false;
boolean IS_RED = false;

if("Blue".equals(holder.mSolved.getText())){
   mSolved.setBackgroundColor(BLUE);
   IS_BLUE = true;
}
if("Red".equals(holder.mSolved.getText())){
   mSolved.setBackgroundColor(RED);
   IS_RED  = true;
}

mSolved.setOnClickListener(new View.OnClickListener() {


    @Override
    public void onClick(View v) {

     if(IS_BLUE)
     {
     mSolved.setBackgroundColor(RED);
     IS_RED  = true;
     IS_BLUE = false;
     }
    else if(IS_RED)
    {
    mSolved.setBackgroundColor(BLUE);
    IS_BLUE = true;
    IS_RED  = false; 

    }

 }

推荐阅读