有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重置按钮到默认背景

我知道已经有人问过了,但已经过时了:

我有两个按钮,代表两个选择,如果选择了一个,背景颜色会变为黄色。但如果我想更改选择,我需要以某种方式重置按钮:

我已经试着把它放回去了,但是一些旧的设计出来了。你能给我现代纽扣样式的身份证吗?告诉我如何实现它

            int myChoice;

            if (view == findViewById(R.id.choice1)){
                myChoice = 1;
                choice1.setBackgroundColor(getResources().getColor(R.color.highlightButton));
                choice2.setBackgroundResource(安卓.R.drawable.btn_default);
            }

            else if (view == findViewById(R.id.choice2)){
                myChoice = 2;
                choice2.setBackgroundColor(getResources().getColor(R.color.highlightButton));
                choice1.setBackgroundResource(安卓.R.drawable.btn_default);
            }


        }

共 (2) 个答案

  1. # 1 楼答案

    将标记与getBackground()一起使用。这将确保你总是回到原来的状态。 在函数开头添加以下内容

    if (v.getTag() == null)
        v.setTag(v.getBackground());
    

    然后使用

    v.setBackground(v.getTag());
    
  2. # 2 楼答案

    here开始,您可以将按钮的默认颜色存储到Drawable中,并将选择颜色(本例中为黄色)抓取到另一个Drawable,然后使用这些Drawable变量切换按钮的背景色

    请查看下面的演示

    public class MainActivity extends AppCompatActivity {
        private Drawable mDefaultButtonColor;
        private Drawable mSelectedButtonColor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final Button btn1 = findViewById(R.id.btn1);
            final Button btn2 = findViewById(R.id.btn2);
    
            mDefaultButtonColor = (btn1.getBackground());
            mSelectedButtonColor = ContextCompat.getDrawable(this, R.color.buttonSelected);
    
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toggleButton(btn1, true);
                    toggleButton(btn2, false);
                }
            });
    
    
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toggleButton(btn1, false);
                    toggleButton(btn2, true);
                }
            });
    
    
        }
    
        private void toggleButton(Button button, boolean isSelected) {
            button.setBackground(isSelected ? mSelectedButtonColor : mDefaultButtonColor);
        }
    
    }