简体   繁体   English

根据以前的颜色更改按钮背景色

[英]Change button background color based on previous color

I have a very simple problem 我有一个非常简单的问题

consider I'm retrieving a string value online using getText() Method 考虑我正在使用getText()方法在线检索字符串值

Now depending upon value of string I have set my button background to red and blue. 现在,根据字符串的值,我将按钮背景设置为红色和蓝色。

If string value is red then button background is red and if it is blue then blue. 如果字符串值为红色,则按钮背景为红色,如果其为蓝色,则为蓝色。

Now if I implement onClicklistener to same button I would like to changes it's Background color. 现在,如果将onClicklistener实现为相同的按钮,我想更改其背景颜色。 If it was Red then change it to blue and if it was blue then change it to red as long as user presses key. 如果它是红色,则将其更改为蓝色,如果它是蓝色,则在用户按下键时将其更改为红色。

 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
 }
}

Try using FLAG variables. 尝试使用FLAG变量。 Something similar to this. 与此类似。

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; 

    }

 }

Try this code: 试试这个代码:

    mSolved = (Button) findViewById(R.id.book_solved);
    mSolved.setBackgroundColor(Color.parseColor("#009900"));
    mSolved.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View tView) {


            ColorDrawable buttonColor = (ColorDrawable) mSolved.getBackground();

            int colorId = buttonColor.getColor();
           // Log.i("INFO", "find color value for new color " + colorId);
            if (colorId == -3407872) {  // color is read
                mSolved.setBackgroundColor(Color.parseColor("#009900"));
            }
            else {

                mSolved.setBackgroundColor(Color.parseColor("#cc0000"));

            }

        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM