【问题标题】:Change background of all buttons on click单击时更改所有按钮的背景
【发布时间】:2015-10-05 19:27:28
【问题描述】:

好的,我正在尝试为我正在为一个项目开发的这款井字游戏设计风格。当我按下新游戏时,我想要某种将每个按钮的背景更改为颜色的数组。然后,当用户单击一个按钮在那里移动时,该空间将根据玩家的不同而变为不同的颜色(我有一个 PlayerTurn 标志变量来确定这一点)。我还想根据与该按钮对应的索引来获取 int 数组中的值。如何为每个按钮分配一个数值,以便以后用于索引到我的数组?

这是我目前正在使用的代码。

    Button buttons[] = new Button[9];
    buttons[0] = (Button) findViewById(R.id.button0);
    buttons[1] = (Button) findViewById(R.id.button1);
    buttons[2] = (Button) findViewById(R.id.button2);
    buttons[3] = (Button) findViewById(R.id.button3);
    buttons[4] = (Button) findViewById(R.id.button4);
    buttons[5] = (Button) findViewById(R.id.button5);
    buttons[6] = (Button) findViewById(R.id.button6);
    buttons[7] = (Button) findViewById(R.id.button7);
    buttons[8] = (Button) findViewById(R.id.button8);

【问题讨论】:

    标签: java android xml button


    【解决方案1】:

    您可以创建Button 类型的ArrayList

    private ArrayList<Button> mList;
    
    onCreate()//
    mList = new ArrayList<>();
    mList.add(yourButton);
    .....................
    
    for(int i = 0 ; i< mList.size(); i++)
      mList.get(i).setBackground(//your color);
    

    【讨论】:

    • 好的,那么我怎样才能确保当我单击中心按钮时,只有那个按钮会改变颜色。
    • 我编辑了我的原始帖子以显示我正在使用的代码。我不熟悉 Arraylist 或它们与 Arrays 的区别。
    • 每个项目都需要使用 OnClickListener
    • 会不会有这样的工作:buttons[i].setOnClickListener(this)
    • 是的,但您仍然需要为每个按钮使用 OnClick 方法
    猜你喜欢
    • 1970-01-01
    • 2013-01-05
    • 2017-02-19
    • 2023-03-15
    • 1970-01-01
    • 2014-10-09
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多