1

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?

dddeee
  • 237
  • 4
  • 12
  • 1
    Possible duplicate of [Java, Simplified check if int array contains int](http://stackoverflow.com/questions/12020361/java-simplified-check-if-int-array-contains-int) – buczek Apr 18 '16 at 21:12
  • Thank you very much fot that link. Even more interesting things that I needed for that task :) – dddeee Apr 18 '16 at 21:37

2 Answers2

2

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()) {
        ...
    }
}
Slobodan Antonijević
  • 2,533
  • 2
  • 17
  • 27
-1

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());
 });
}
Jikky
  • 5
  • 2
  • Actually value.getId() WILL return the same value as R.id.XXX of the clicked View, so you're incorrect. The problem is that he cannot use Arrays.asList on int. – Slobodan Antonijević Apr 18 '16 at 21:25