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

Android

Android Problem Overview


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:

  <Button
      android:id="@+id/add_04"
      android:layout_width="42dp"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:layout_marginLeft="15dp"
      android:background="@xml/zbuttonshape"
      android:onClick="onClick"
      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 = R.id.class.getFields();
for(Field f:campos){
	 try{
	    if(v.getId()==f.getInt(null)){
	    	name5 = f.getName();
	    	break;
	    }
	   }
	   catch(Exception e){
	    e.printStackTrace();
	}
}

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

Thanks in advance.

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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. A word of caution though, tags are not unique in Android, watch for accidental tag collisions within the same view tree.

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.

Solution 3 - Android

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());

Solution 4 - Android

You can check id of each button such way:

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.add_04:
        Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
        break;
    case R.id.add_05:
        Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
        break;
    }
}

Solution 5 - Android

   Use this Approach to get View Id by Programming .
  <TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    />


    String id=getResources().getResourceEntryName(textView.getId());
    Toast.makeText(this,id,Toast.LENGTH_LONG).show();

You will get Result ; tv

Solution 6 - Android

You can put this toString() inside an Android View, it will return the String resource Id.

@Override
public String toString() {

    Context context;
    Resources r = null;

    context = getContext();

    if (context != null) {
        r = context.getResources();
    }

    String entryName = null;

    if (r != null)
        entryName = r.getResourceEntryName(getId());

    return entryName;
}

Solution 7 - Android

Kotlin version (from @gadget) as view extension:

val View.stringId: String
    get() {
        return if (this.id == -0x1)
            "no-id"
        else
            this.resources.getResourceName(this.id)
    }

Solution 8 - Android

It's a late answer but may useful someone looking out for a way to get the resource id (int) for any view / drawable / String programmatic.

image from res/drawable

int resID = getResources().getIdentifier("my_image", 
			"drawable", getPackageName());

view based on resource name

int resID = getResources().getIdentifier("my_resource", 
			"id", getPackageName());

string

int resID = getResources().getIdentifier("my_string", 
			"string", getPackageName()); 

Solution 9 - Android

The answer by @King of Masses is great. Here is my in Kotlin:

image from res/drawable

val viewId = context.resources.getIdentifier("my_image", "drawable", context.packageName)

view based on resource name

val viewId = context.resources.getIdentifier("my_textview_id", "id", context.packageName)

string

val viewId = context.resources.getIdentifier("my_string", "string", context.packageName)

Layout

val viewId = context.resources.getIdentifier("my_custom_layout", "layout", context.packageName)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichalView Question on Stackoverflow
Solution 1 - AndroidgadgetView Answer on Stackoverflow
Solution 2 - AndroidSeva AlekseyevView Answer on Stackoverflow
Solution 3 - AndroidBlackbeltView Answer on Stackoverflow
Solution 4 - AndroiddilixView Answer on Stackoverflow
Solution 5 - AndroidZafar HussainView Answer on Stackoverflow
Solution 6 - AndroidtausiqView Answer on Stackoverflow
Solution 7 - AndroidGabrielView Answer on Stackoverflow
Solution 8 - AndroidKing of MassesView Answer on Stackoverflow
Solution 9 - AndroidThiagoView Answer on Stackoverflow