簡體   English   中英

如何更改單擊的按鈕的顏色,但使其只能同時更改一個按鈕的顏色?

[英]How can I change the color of a button that is clicked but make it so that only one buttons' color can be changed at the same time?

我怎樣才能做到這一點,而不是在單擊按鈕時顯示文本,而是每個按鈕的背景顏色發生變化,並且同時只有一個按鈕可以是該顏色?

package com.example.scrolltes1;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.KeyEventDispatcher;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import static android.graphics.Color.BLUE;
import static android.graphics.Color.GRAY;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    boolean constrain = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button1:
                    Toast.makeText(this, "Button 1 clicked", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.button2:
                    Toast.makeText(this, "Button 2 clicked", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.button3:
                    Toast.makeText(this, "Button 3 clicked", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

是否可以用改變背景顏色的東西替換 Toast.makeText 括號內的所有內容?

您可以為每個按鈕創建具有特定顏色的自定義布局:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button1
        Toast ToastMessage = Toast.makeText(this,"Button 1 clicked", Toast.LENGTH_SHORT);
        View toastView = ToastMessage.getView();
        toastView.setBackgroundResource(R.layout.custom_color);
        ToastMessage.show();
        break;

    // more cases
    }
   }

有關解決方案的更多詳細信息,請參閱本文: https://www.android-examples.com/change-toast-message-background-color-in-android/

如果這有幫助,請不要猶豫接受它作為答案:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM