android中的setBackgroundColor

前端之家收集整理的这篇文章主要介绍了android中的setBackgroundColor前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在这个简单的游戏中,我想改变我按下的按钮的背景颜色.但是我得到以下结果,按钮外观变得不好(形状变得不同):
pressedButton.setBackgroundColor(Color.RED);

有没有更好的方法呢?谢谢.

[编辑:我的完整代码]

package com.example.xo_game;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    Button[] btns;
    char[][] gameState = new char[3][3];
    char turn = 'X';

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

        Button[] btns = new Button[9];

        btns[0] = (Button) findViewById(R.id.btn1);
        btns[1] = (Button) findViewById(R.id.btn2);
        btns[2] = (Button) findViewById(R.id.btn3);

        btns[3] = (Button) findViewById(R.id.btn4);
        btns[4] = (Button) findViewById(R.id.btn5);
        btns[5] = (Button) findViewById(R.id.btn6);

        btns[6] = (Button) findViewById(R.id.btn7);
        btns[7] = (Button) findViewById(R.id.btn8);
        btns[8] = (Button) findViewById(R.id.btn9);

        for (int i = 0; i < 9; i++) {
            btns[i].setTag(i);
            btns[i].setOnClickListener(clickListener);
            gameState[i / 3][i % 3] = 'E';
        }
    }

    View.OnClickListener clickListener = new View.OnClickListener() {

        public void onClick(View v) {
            Button pressedButton = (Button) v;

            int indexOfPressedButton = Integer.parseInt(pressedButton.getTag()
                    .toString());

            int row = indexOfPressedButton / 3;
            int col = indexOfPressedButton % 3;

            if (gameState[row][col] != 'E')
                return;

            gameState[row][col] = turn;

            String turnAsString = String.valueOf(turn);

            pressedButton.setText(turnAsString);

            if (turn == 'X') {
                pressedButton.setBackgroundColor(Color.RED);
                turn = 'O';
            } else {
                pressedButton.setBackgroundColor(Color.GREEN);
                turn = 'X';
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main,menu);
        return true;
    }
}

解决方法

pressedButton.getBackground().setColorFilter(Color.RED,PorterDuff.Mode.MULTIPLY);
原文链接:https://www.f2er.com/android/313826.html

猜你在找的Android相关文章