ivesingh
ivesingh

Reputation: 888

Detect what button was pressed?

I have 26 different buttons containing alphabets. In which I want if button that contains D, I, L should show the image button if any other button is clicked then something else happens. Below is what I have tried but this doesn't seem to be working. I am aware of onTouchKeyListener() but it might be really huge of coding.

imgD.setVisibility(View.INVISIBLE);
imgI.setVisibility(View.INVISIBLE);
imgL.setVisibility(View.INVISIBLE);

            if(d.isPressed()) {
                imgD.setVisibility(View.VISIBLE);
            }

Upvotes: 0

Views: 3143

Answers (4)

codeMagic
codeMagic

Reputation: 44571

One way to do it is to add the same function to each button in xml

android:onClick="someFunction"

then in Java

public void someFunction(View v)
{
     TextView tv = (TextView)v;   // cast the View clicked to a Button
     String text = v.getText().toString();  // get the text of the Button
     if ("D".equals(text) || "I".equals(text) || "L".equals(text))   // See if it matches
     {
         imgD.setVisibility(View.VISIBLE);
         imgI.setVisibility(View.VISIBLE);
         imgL.setVisibility(View.VISIBLE);
     }
}

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

You can set a tag for each button and then use that as a key into a map from string to image button. That way you can use a single click listener (or onClick method) and easily get the appropriate image. In code, you would use the setTag(Object) method. In XML, you can use the android:tag="value" attribute.

Map<Object, ImageButton> buttonMap = new HashMap<Object, ImageButton>();
// initialize the map

// later:
public void onClick(View v) {
    ImageButton btn = buttonMap.get(v.getTag());
    if (btn != null) {
        btn.setVisibility(View.VISIBLE);
    }
}

Instead of a Map, you could set the button tags and the image button tags and use findViewWithTag() to find the image button corresponding to the clicked button.

public void onClick(View v) {
    View btn = findViewWithTag("img" + v.getTag());
    if (btn != null) {
        btn.setVisibility(View.VISIBLE);
    }
}

Upvotes: 3

Anson Yao
Anson Yao

Reputation: 1584

If you put buttons in your xml file, put android:onclick attribute in all buttons and link to same function:

  android:onclick="myButtonOnClick"

Then in your java code, i.e., the activity which contains these buttons,

  public void myButtonOnClick(View v){
       switch(v.getId()){

       }

       // put your logic here. 

  }

Upvotes: 1

Mansour Fahad
Mansour Fahad

Reputation: 48

I recommend to use onTouchKeyListener() with a switch statement.

Upvotes: 0

Related Questions