Question

Hello guys i am making simple game that can take point if i click right button. so there is 5 imagebutton and 1 textview. textview will generate random number 1-5 . and those 5 imagebuttons has 5 different id , so my point is if textview generates 1 number how can i check it its right button using if statement.

if ( textview(current generated number ) == imagebutton(id) ) {
 counter++)

something like this can you help me guys? example code would be nice :D

Was it helpful?

Solution

Set the tag value for the buttons either from xml set Tag attribute

Tag = "1"

or

btn.setTag("1");

Add the buttons corresponding value to its tag and then compare it with tags value

in onClick method you get id of button clicked

Button btn = (Button) findViewById(id); 
string valu = btn.getTag();

Now compare the textView value with this tag value.

string txt = textView.getText();

if(txt.equals(valu))
{
// do what you want
}

OTHER TIPS

You could store the button resource IDs an array of int. Then in a common click handler, you could test whether the button clicked was the same as the one randomly selected. Here's a simplistic, minimal example. It assumes you've set and displayed the random number before you get the button clicks.

In your class, define these fields:

private int myButtons[] = null;
private int randomNumber = 0;

In onCreate(), add the following:

myButtons = new int[] {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4}; 

Add the method:

public btnClick(View v) {

    if (findViewById(myButtons[randomNumber]) == v)
        Log.i(TAG, "Correct!");
    else
        Log.i(TAG, "Incorrect!");
}

Then in your layout XML, define the buttons with your click handler:

<Button
    android:id="@+id/btn0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="@string/btn0" />

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="@string/btn1" />

<Button
    android:id="@+id/btn2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="@string/btn2" />

<Button
    android:id="@+id/btn3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="@string/btn3" />

<Button
    android:id="@+id/btn4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="@string/btn4" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top