ahooee
ahooee

Reputation: 275

How to change InlineKeyboardButton label on user click?

I want to change the label of InlineKeyboardButton object that initialized by setText() method ,after it clicked

For example,‌changing the "label" string to "label-1" By clicking the button.

This is a piece of my code:

if (update.hasMessage() && update.getMessage().hasText()) {
    if (update.getMessage().getText().equals("/start")) {
        long chat_id = update.getMessage().getChatId();
        message = new SendMessage() 
                .setChatId(chat_id)
                .setText("You send /start");
        InlineKeyboardButton dk1=new InlineKeyboardButton().setText("labe1").setCallbackData("change_the_label");
        InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
        List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
        List<InlineKeyboardButton> rowInline = new ArrayList<>();
        rowInline.add(dk1);
        rowsInline.add(rowInline);
        markupInline.setKeyboard(rowsInline);
        message.setReplyMarkup(markupInline);
        try {execute(message); catch (TelegramApiException e) {e.printStackTrace();}}}

Upvotes: 1

Views: 2834

Answers (1)

ahooee
ahooee

Reputation: 275

I solved the problem by adding this piece of code that uses a EditMessageReplyMarkup object to edit existing inline keyboard :

   String call_data = update0.getCallbackQuery().getData();
            long message_id = update0.getCallbackQuery().getMessage().getMessageId();
            long chat_id = update0.getCallbackQuery().getMessage().getChatId();
            String inline_message_id = update0.getCallbackQuery().getInlineMessageId();
            if (call_data.equals("change_the_label")) {
                String answer = "Updated message text";
                EditMessageReplyMarkup new_message = new EditMessageReplyMarkup()
                        .setChatId(chat_id).setMessageId(toIntExact(message_id))
                        .setInlineMessageId(inline_message_id);
                InlineKeyboardButton dk1=new InlineKeyboardButton();
                dk1.setText("label1");
                dk1.setCallbackData("change_the_label");
                InlineKeyboardMarkup markupInline = new InlineKeyboardMarkup();
                List<List<InlineKeyboardButton>> rowsInline = new ArrayList<>();
                List<InlineKeyboardButton> rowInline = new ArrayList<>();

                rowInline.add(dk1);

                rowsInline.add(rowInline);

                markupInline.setKeyboard(rowsInline);
                new_message.setReplyMarkup(markupInline);

                                try {editMessageReplyMarkup(new_message);

                } catch (TelegramApiException e) {
                    e.printStackTrace();
                }

Upvotes: 1

Related Questions