dddeee
dddeee

Reputation: 247

I want to put IDs of few buttons to an array and then check them in if condition

this is my code:

xml

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="8"
    android:id="@+id/button8"
    android:layout_alignTop="@+id/button7"
    android:layout_toRightOf="@+id/button7"
    android:layout_toEndOf="@+id/button7" />

as you can see I have buttons (its going to be a calculator) with text(1-9) and id=button 1-9

in MainActivity I made an array:

private int[] numbers = {
        R.id.button0,
        R.id.button1,
        R.id.button2,
        R.id.button3,
        R.id.button4,
        R.id.button5,
        R.id.button6,
        R.id.button7,
        R.id.button8,
        R.id.button9,
};

And now I want to make specific actions only if those ID buttons were clicked. For example:

 public void onClick(View value) {
     if (Arrays.asList(numbers).contains(value.getId())) {
            Button button = (Button) value;
            textField.append(button.getText());

But it does not work. I assume Arrays.asList(numbers).contains(value.getId()) is a problem. Tried to type only value without getId(), and doesn't work as well. I tried to look help here and on google but I couln't find anything helpful. Any help?

Upvotes: 1

Views: 89

Answers (2)

Slobodan Antonijević
Slobodan Antonijević

Reputation: 2643

Arrays.asList will not return boolean on primitive variables (like int). Use ArrayUtils.contains(array, key) instead

public void onClick(View value) {
    if (ArrayUtils.contains(numbers, value.getId()) {
        ...
    }
}

Upvotes: 2

Jikky
Jikky

Reputation: 5

If you only type .contains(value) this won't work obviously because then you search your array list that contains ints for a View. The problem you have is that value.getID() does not return the R.id.XXX.

I would suggest you just add a OnClickListener to each of the buttons and pack it into a for-loop. Like:

for(every button){
 button.setOnClickListener(new OnClickListener(){
  textField.append(button.getText());
 });
}

Upvotes: -1

Related Questions