Brownman Revival Brownman Revival - 2 months ago 8
Android Question

Get button ID not entire button

ArrayList<View> allButtons;
String button;
button = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables().toString();

System.out.println(button);


Outputs:


System.out: [android.support.v7.widget.AppCompatImageButton{7107785 VFED..C.. ........ 32,74-176,210 #7f0b0056 app:id/imageButton2}, android.support.v7.widget.AppCompatButton{c4b99da VFED..C.. ...P.... 66,256-242,352 #7f0b0057 app:id/button}]


How can i get just the id which is
button

Answer

You should write your code a s

ArrayList<View> allTouchables = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables();
for (View view : allTouchables) {
    System.out.println(view.getId());
}

As above code returns all touchable views present into given container, you should also check about the type of view like

ArrayList<View> allTouchables = ((RelativeLayout) findViewById(R.id.activity_main)).getTouchables();
for (View touchable : allTouchables) {
   // To check if touchable view is button or not
    if( touchable instanceof Button) {
        System.out.println(touchable.getId());
    }
}

To get string representation of id, you can write

String idString = view.getResources().getResourceEntryName(view.getId());
Comments