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

like this:

/**
 * @return "[package]:id/[xml-id]"
 * where [package] is your package and [xml-id] is id of view
 * or "no-id" if there is no id
 */
public static String getId(View view) {
    if (view.getId() == View.NO_ID) return "no-id";
    else return view.getResources().getResourceName(view.getId());
}

I use this in view constructors to make more meaningful TAGs


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.

EDIT much later: the OP's issue was a case of an XY problem. That said, the question title alone is a legitimate question in its own right.


Edit:

You have to use

getResources().getResourceEntryName(int resid);

If you want to retrieve the entry name associated to a resId

or

You can use getIdentifier() to retriece a resource identifier for the given resource name.

For instance:

int id = this.getResources().getIdentifier("yourtext", "string", this.getPackageName());

Tags:

Android