Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

android - Accessing buttons in a GridLayout in Java?

I am making a hangman game, in the main Activity, there is a GridLayout containing the buttons for each letter. I would like to set a Button array in java to include all of the buttons and access them (in order to use them in java methods, as my teacher instructed us). My question is, what would be the easiest way to identify the buttons in Java, and how can I add them to said Button array? Thanks in advance. This is my first question here.

EDIT

The letters are not English letters and in this picture you can see the design of the GridLayout.

the design of the GridLayout

Notice that the language direction is RTL instead of LTR which means I used a reverse order of the columns.

So, in addition to my first question, is there any way to 'reverse' the numbers' order from LTR to RTL?

question from:https://stackoverflow.com/questions/65891730/accessing-buttons-in-a-gridlayout-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need an array to identify the buttons. Use an array to identify just the buttons that was pressed.

If your button contains the letter as a text...:

<Button
        android:id="@+id/alef_button"
        ...
        android:text="?" />

<Button
        android:id="@+id/bet_button"
        ...
        android:text="?" />

Then you can use the same method as a listener for all buttons:

public void onButtonClick(View view) {
    Button pressedButton = (Button) view;
    if("?".equals(pressedButton.getText())) {
        putOnArray("alef");
    } else if("?".equals(pressedButton.getText())) {
        putOnArray("bet");
    } ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...