Mehran Khan
Mehran Khan

Reputation: 90

How to store a button name in a variable ? I found this query a challenging one for me

Here is a scenario, for example, I have an Image Button named as a_1 in android. I want to store that button name in a variable i.e. variable = a_1 so that I can pass it to a method and use it in that method i.e. variable.set_Image_Resource(...). Is this possible? If so, your ideas will be appreciated. If not, any alternate solution will be appreciated. I have searched a lot on many platforms but nothing useful found except storing button-text in a variable.

The reason of such question is, I have 64 Image-Buttons in my application and there is a scenario where 32-buttons have a switch statement on them. If I go to implement all the 64-buttons with 32 switches and each switch has 32 cases, that will be a crazy approach. So, what I want to do is, I want to make just one method which have just one switch, in which I pass the button and instead of using the button qualifier i.e. button_name.something() I can use that parameter i.e. parameter.something().

I know there are many other ways to implement this problem but I am supposed to solve this problem in this way.

Upvotes: 0

Views: 136

Answers (3)

TAM
TAM

Reputation: 1741

Another elegant way would be to declare those buttons not via an XML view definition, but programmatically by adding them to the enclosing view via addView(...). That way you can organize them in an array or list and simply iterate over them.

Upvotes: 0

Gorio
Gorio

Reputation: 1646

I don't know if i understood your question, but if you want to get all Buttons Id/text you need to do this code.

LinearLayout layout = (LinearLayout) findViewById(R.id.layout);

for(int i=0; i < layout.getChildCount(); i++)
{
    View v = layout.getChildAt(i);

    if (v instanceof Button) {
        Button b = (Button) v;
        Log.d("GORIO", "ID: " + b.getId());
        Log.d("GORIO", "Button Text: " + b.getText());
    }
}

Upvotes: 0

Benjam&#237;n Molina
Benjam&#237;n Molina

Reputation: 211

I believe you can solve this issue by binding all your buttons to the same ClickListener, so you don't have to get the id of the button as string. Inside that listener, you can have your switch. Here is an example of how you can create a ClickListener class:

public class MyListener implements View.OnClickListener {

    public final static String TAG = "ListenerTAG_";

    MainActivity context;

    public MyListener(MainActivity context){
        this.context = context;
    }

    @Override
    public void onClick(View v) {
        Button b = (Button) v;
        // Do stuff with the pushed button
    } 
}

On the onCreate of your activity, you declare an instance of this listener and add it to each button.

Hope it helps.

Upvotes: 1

Related Questions