new keyboard code

This commit is contained in:
mrbesen 2021-01-12 13:33:19 +01:00
parent 6ca91303b3
commit d359b89851
Signed by: MrBesen
GPG Key ID: 596B2350DCD67504
1 changed files with 42 additions and 13 deletions

View File

@ -1,27 +1,31 @@
package de.mrbesen.telegram.objects;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class TInlineKeyboardMarkup implements TReplyMarkup {
ArrayList<JSONArray> arr_btn = new ArrayList<>();
List<JSONArray> arr_btn;
public TInlineKeyboardMarkup() {
this(1);
}
}
/**
* @param rows is a hint, how many lines will be needed
*/
public TInlineKeyboardMarkup(int rows) {
if(rows < 1)
throw new IllegalArgumentException("You need at least one row.");
arr_btn = new ArrayList<JSONArray>();
for( int row = 0; row < rows; row++ ) {
arr_btn.add(new JSONArray());
arr_btn = new ArrayList<>(rows);
for(int row = 0; row < rows; ++row) {
arr_btn.add(row, new JSONArray());
}
}
/**
* Insert button in first line
* @param title
@ -36,19 +40,43 @@ public class TInlineKeyboardMarkup implements TReplyMarkup {
* Insert button in nth line
* @param title
* @param url
* @param row
* @param row (1 indexed)
* @return
*/
public TInlineKeyboardMarkup addUrlButton(String title, String url, int row) {
arr_btn.get(row-1).put(new JSONObject().put("text", title).put("url", url));
addButton(row, new JSONObject().put("text", title).put("url", url));
return this;
}
/**
* insert button in nth line
* @param title
* @param callback
* @param row (1 indexed)
* @return
*/
public TInlineKeyboardMarkup addCallbackButton(String title, String callback, int row) {
arr_btn.get(row-1).put(new JSONObject().put("text", title).put("callback_data", callback));
addButton(row, new JSONObject().put("text", title).put("callback_data", callback));
return this;
}
/**
* Add a button, check if the row is available first
* @param row
* @param btn
*/
private void addButton(int row, JSONObject btn) {
--row;
if(arr_btn.size() < row) {
//row existiert noch nicht
row = arr_btn.size(); //auf nächst größte Zeile setzten, damit keine leerzeilen entstehen
//resize
arr_btn.add(row, new JSONArray());
}
JSONArray arr = arr_btn.get(row);
arr.put(btn);
}
public static TInlineKeyboardMarkup makeYesNo(String yes, String no) {
return makeYesNo(yes, no, "");
}
@ -69,6 +97,7 @@ public class TInlineKeyboardMarkup implements TReplyMarkup {
@Override
public String toJSONString() {
arr_btn.removeIf(a -> a.isEmpty()); //remove empty rows
return new JSONObject().put("inline_keyboard", new JSONArray(arr_btn)).toString();
}
}