Richal Richal - 1 year ago 107
Android Question

Easier way to get view's Id (string) by its Id (int)

I'm new with android and java, so sorry if it's a too basic question but I've tried to find a solution in the forums and google and I couldn't.

I have 24 buttons in my layout, all these buttons do something similar so I want to create a generic function. But first I need to know the name (xml id) of he button.

This the XML code of the button:

android:text="@string/mas" />

I set android:onClick="onClick" for all the buttons.

In my activity I've create a new function onClick:

This the code I've tried:

public void onClick(View v) {
String name = v.getContext().getString(v.getId());
String name2 = context.getString(v.getId());
String name3 = getString(v.getId());
String name4 = getResources().getString(v.getId());

But when I try to get the name (in this case "add_04") I always get "false".

Finally I've found a solution with the following code:

import java.lang.reflect.Field;

String name5 = null;
Field[] campos =;
for(Field f:campos){
name5 = f.getName();
catch(Exception e){

My question is if Is not there an easier way to get this ID?

Thanks in advance.

Answer Source

The approach is misguided to begin with. If you want to associate a piece of arbitrary data (e. g. a string) with a view, that's what tag is for. The ID is numeric and it better stay that way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download