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