Как получить символ от кнопки для редактирования текста? - PullRequest
0 голосов
/ 05 мая 2020

этот код работает очень хорошо, он генерирует три кнопки, потому что у меня есть три элемента «car» и элементы случайного выбора: button_1 «a», button_2 «r», button_3 «c», моя проблема в том, когда я нажимаю на каждая кнопка, которую он набирает в тексте редактирования, стала "aaa"

//the problem was here (var button)

    edittext.setText(edittext.getText().toString() + button.getText());

я пытаюсь заставить игру угадывать слово

    String array[]= {"car"};


    int random = (int) (Math.random() * array.clone().length);

    StringBuilder word = new StringBuilder(array[random]);


    for (int i = 0; i < array[random].length(); i++) {

        char id = 'b';
        final Button button = new Button(this); //local var
        button.setId(id + i);
        linearLayout.addView(button);


        int randIndex = new Random().nextInt(word.length());
        button.setText("" + word.charAt(randIndex));
        word.deleteCharAt(randIndex);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //******the problem was here (var button)

                button.setVisibility(View.INVISIBLE);

                edittext.setText(edittext.getText().toString() + button.getText());
            }
        });

    }

1 Ответ

0 голосов
/ 05 мая 2020

Адресация следующих вещей:

  1. Создайте List индексов от 0 до array[random].length() - 1 и перемешайте его, используя Collections::shuffle. Затем вы можете использовать перетасованные индексы для установки метки кнопки.
  2. Объявить массив Button вне l oop и инициализировать массив внутри l oop.
String array[] = { "car" };

int random = (int) (Math.random() * array.length);
List<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < array[random].length(); i++) {
    indices.add(i);
}
Collections.shuffle(indices);
Button[] btn = new Button[array[random].length()];
for (int j = 0; j < array[random].length(); j++) {
    char id = 'b';
    btn[j] = new Button(this);
    btn[j].setId(id + j);
    linearLayout.addView(btn[j]);
    btn[j].setText("" + names_ofcolor[random].charAt(indices.get(j)));
    btn[j].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btn[j].setVisibility(View.INVISIBLE);
            edittext.setText(edittext.getText().toString() + btn[j].getText());
        }
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...