如何在单击按钮的文本时将其移动到另一个按钮的文本

时间:2017-12-03 15:14:54

标签: java android

enter image description here制作简单的益智游戏,数字按钮放置4x4。当按下按钮时,它应该用对角线按钮的文本改变文本。我洗了数字。转换按钮的文字我遇到了问题。 这是4x4益智游戏的代码。

这里是我的代码

private LinearLayout buttonsContainer;
private Button[][] buttons = new Button[4][4];
private Button restartButton;
private List<Integer> numberList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buttonsContainer = findViewById(R.id.buttonsContainer);
    restartButton = findViewById(R.id.restartButton);
    restartButton.setOnClickListener(this);

    for (int i = 0; i < 4; i++) {
        LinearLayout rows = (LinearLayout) buttonsContainer.getChildAt(i);
        for (int j = 0; j < 4; j++) {
            buttons[i][j] = (Button) rows.getChildAt(j);
        }
    }

    for (int i = 1; i <= 15; i++) {
        numberList.add(i);
    }
    restartGame();
}


@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.restartButton: {
            restartGame();
            break;
        }
        case R.id.buttonsContainer:{

            break;
        }
    }
}

private void restartGame() {
    Collections.shuffle(numberList);
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if(i==3 && j==3)continue;
            buttons[i][j].setText(String.valueOf(numberList.get(4*i+j)));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

只是做:

String s = button1.getText();
button1.setText(button3.getText());
button3.setText(s);

单击按钮时。