Roberto
Roberto

Reputation: 21

Converting String value to button name

In VB, you use CType to convert a string to a control's name

Dim btn1 as Button
Dim Str as String ="btn1"
CType((Str), Button).Text ="your text"

how can I achieve the same in java?

Upvotes: 0

Views: 1565

Answers (2)

forpas
forpas

Reputation: 164234

If you have buttons with ids (names) like btn1, btn2, ...., btn20 and you want to set their text via a for loop, you can use getIdentifier() like this:

for (int i = 1; i <= 20; i++) {
    int id = getResources().getIdentifier("btn" + i, "id", getPackageName());
    Button button = findViewById(id);
    button.setText("something" + i);
}

The method getIdentifier() takes the id (name) of a View and returns its integer id.
Then with findViewById(id) you get a reference to that View.
You may need to qualify both getResources() and getPackageName() with a valid Context if your code is not inside an activity class, like this:

int id = context.getResources().getIdentifier("btn" + i, "id", context.getPackageName());

Upvotes: 2

MikeT
MikeT

Reputation: 57103

If you mean set the text displayed by the Button, then something like :-

    Button btn1 = this.findViewById(R.id.done); // Gets the Button as per the id in the layout.
    btn1.setText("Your Text");
  • in some older versions of Android Studio you had to specifically cast the type from the findViewById, as such the above use Button btn1 = (Button) this.findViewById(R.id.done);

Additional re Comment :-

I have up to 20 buttons btn1.........btn20 then i want to use loop to reference this buttons which means i need a string for the btn and an Integer for the number. Concatenating the string & integer will give me the actual button name.

I believe the following may be along the lines of what you want. This creates 20 buttons, adding them to the layout.

Each will have two fields/members set. - The Text (the text displayed by the button) field will be set to My Button #? (where ? will be 1-20) - The Tag (a field that can be used as wanted) will be set to a String that is the respective Button's offset in the ArrayList (i.e 0-19).

Each will have an onClickListener added that will issue a Toast detailing the Button's values for the Text and the Tag.

Additionally, the reference a button is achieved by searching for the button accoring to either it's Text value or it's Tag value. Two examples are given where the 0 is searched for, first in the Tag value (will be found as 0) and then in the Text value (will not be found). The result is written to the Log.

public class OtherActivity extends AppCompatActivity {

    ArrayList<Button> mButtons = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        LinearLayout mMainLayout = this.findViewById(R.id.mainlayout);

        // Add the 20 buttons dynamically assigning Text and a Tag
        for (int i=0; i < 20; i++) {
            Button current_button = new Button(this);
            current_button.setText("My Button #" + String.valueOf(i + 1));
            current_button.setTag(String.valueOf(i));
            mButtons.add(current_button);
            mMainLayout.addView(current_button);
            current_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(
                            v.getContext(),
                            "You CLicked on the Buttton with Text as :-" + ((Button) v).getText().toString() + " Tag as " + ((Button)v).getTag(),
                            Toast.LENGTH_SHORT
                    ).show();
                }
            });
        }

        // Search for the button according to some text    
        // Should work as Tag has been set to 0
        Button button_to_use = findButtonByTagOrText("0",true,mButtons);
        if (button_to_use != null) {
            Log.d("BUTTONFINDRESULT","Button 0 Found according to the Tag");
        } else {
            Log.d("BUTTONFINDRESULT","Button 0 NOT FOUND acording to Tag");
        }

        //Will not find button as text will not be o but will instead be My Button #1 (for the first button)
        button_to_use = findButtonByTagOrText("0", false,mButtons);
        if (button_to_use != null) {
            Log.d("BUTTONFINDRESULT","Button 0 Found according to the Text");
        } else {
            Log.d("BUTTONFINDRESULT","Button 0 NOT FOUND acording to Text");
        }
    }

    /**
     * Find the button according to it's TAG or Text
     * @param value_to_find     The String to find
     * @param look_for_tag      true if to look at the Tag, false if to look at the Text
     * @param button_list       The ArrayList<Button> aka the list of buttons
     * @return                  null if not found, else the Button object
     */
    private Button findButtonByTagOrText(String value_to_find, boolean look_for_tag, ArrayList<Button> button_list) {
        Button rv = null;
        String compare_string;
        for (Button b: button_list) {
            if (look_for_tag) {
                compare_string = (String) b.getTag();
            } else {
                compare_string = b.getText().toString();
            }
            if (value_to_find.equals(compare_string)) {
                return b;
            }
        }
        return rv; // Note returned button will be null if text not found.
    }
}

The result is that the App when run appears as :-

enter image description here

  • Note the DONE button was in the layout, it can be ignored as it isn't used or handled in the code above.

CLicking a buttons displays a Toast according to the button clicked e.g. :-

enter image description here

The Log includes (as expected) :-

04-13 22:41:20.068 15617-15617/? D/BUTTONFINDRESULT: Button 0 Found according to the Tag
04-13 22:41:20.068 15617-15617/? D/BUTTONFINDRESULT: Button 0 NOT FOUND acording to Text

Upvotes: 0

Related Questions