Android : ImageView getID(); returning integer - android

I've set up an onTouch class to determine when one of my 40 buttons is pressed.
The problem I am facing is determining which button was pressed.
If I use:
int ID = iv.getId();
When I click on button "widgetA1"
I receive the following ID:
2131099684
I would like it to return the string ID "widgetA1"
from:game.xml
<ImageView android:layout_margin="1dip" android:id="#+id/widgetA1" android:src="#drawable/image" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
from:game.java
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView)v;
int ID = iv.getId();
String strID = new Integer(ID).toString();
Log.d(TAG,strID);
//.... etc
}
+-+-+-+-+-+-
I other wise works fine, it knows what button you are pressing. I am quite new to this Android JAVA. Let me know if you guys can help me.

Edit - TL;DR:
View v; // handle to your view
String idString = v.getResources().getResourceEntryName(v.getId()); // widgetA1
Original:
I know it's been a while since you posted, but I was dealing with a similar problem and I think I found a solution by looking at the Android source code for the View class.
I noticed that when you print a View (implicitly calling toString()), the data printed includes the ID String used in layout files (the one you want) instead of the integer returned by getId(). So I looked at the source code for View's toString() to see how Android was getting that info, and it's actually not too complicated. Try this:
View v; // handle to your view
// -- get your View --
int id = v.getId(); // get integer id of view
String idString = "no id";
if(id != View.NO_ID) { // make sure id is valid
Resources res = v.getResources(); // get resources
if(res != null)
idString = res.getResourceEntryName(id); // get id string entry
}
// do whatever you want with the string. it will
// still be "no id" if something went wrong
Log.d("ID", idString);
In the source code, Android also uses getResourcePackageName(id) and getResourceTypeName(id) to build the full string:
String idString = res.getResourcePackageName(id) + ":" + res.getResourceTypeName(id)
+ "/" + res.getResourceEntryName(id);
This results in something to the effect of android:id/widgetA1.
Hope that helps!

You cannot get that widgetA1 string...You will always get an integer. But that integer is unique to that control.
so you can do this to check, which button is pressed
int ID = iv.getId();
if(ID == R.id.widgetA1) // your R file will have all your id's in the literal form.
{
}

Xml
android:tag="buttonA"
Src
Button.getTag().toString();

Of course you can get widgetA1, simply do:
ImageView iv = (ImageView)v;
int id = iv.getId();
String idStr = getResources().getResourceName(id);
It should give you your.package.name:id/widgetA1, then do what you want with that string.

We will get the Integer value corresponds to the views id. For finding on which button you are clicking, better to use tags. you can set tag in the layout xml file and can compare which item you have clicked using.
<Button
android:id="#+id/btnTest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:tag="btntestTag"/>
This is sample usage.

i think that you can use this
try it
ImageView imgView = new ImageView(this);
String imgName = "img"//in your case widgetA1
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());

For the implementation you could use the hint attribute to store the button name, which is accessible. For example in the button code (.xml file) use the following line:
android:hint="buttonName"
Then in the onClicked function (.java file), write the following to get the hint:
String hint = ((Button)v).getHint().toString(); //v is the view passed onClick

Related

How can I get image's name?

I want to make a function which debug when image's name equal "aaa". So I think that I should get image's name.
for example, there is a ImageView.
ImageView img1 = (ImageView) findViewById(R.drawable.button);
public void passMSg(){
if(name == "button"){ // "name" means image's name. = button
Toast. ~
}
I find other questions. But I can't understand and I think that is not answer which I want. Who can help me?
if your image is a file like 'aaa.jpg/png..'
try to use the APIs of String such as subString().indexOf()
and your code may be like this:
int index = name.indexOf(".");
String name = name.subString(name,0,index);
If you assigned a tag for your ImageView then you can get it like this
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:tag="aaa" />
ImageView v = (ImageView)findViewbyId(R.id.img);
String backgroundImageName = String.valueOf(v.getTag());

Get view name programmatically in Android

I am doing a small library to encapsulate adapters functionality and I need get the name of a view programmatically. For example:
<ImageView
android:id="#+id/**ivPerson**"
android:layout_width="80dp"
android:layout_height="80dp"/>
Now, in the code I have the view (ImageView) and I need obtain the name of the view --> ivPerson. I can obtain the id with view.getId() but that's not what I need.
It is possible?
I tried with this:
String name = context.getResources().getResourceEntryName(view.getId());
But not work.
You can use getResourceName(...) instead.
String fullName = getResources().getResourceName(view.getId());
But there is a some problem. This method will give you a full path of view like: "com.google:id/ivPerson"
Anyway, you can use this trick to get only name of a view:
String fullName = getResources().getResourceName(view.getId());
String name = fullName.substring(fullName.lastIndexOf("/") + 1);
Now name will be exactly "ivPerson"
You can do it by setting tag as the id i.e android:tag="ivPerson"
and use String name = view.getTag().toString() to get the name of the tag
For the View v get its name as follows:
String name = (v.getId() == View.NO_ID) ? "" :
v.getResources().getResourceName(v.getId()).split(":id/")[1];
If the view v has no name, then the name is an empty string "".
There is no way to get ivPerson id using getId() or any other method, however you can get it by setting tag value as mentioned in rahul's answer
set tag in xml :
android:tag="ivPerson"
fetch it in your activity
view.getTag().toString();
You may do something like this:
for(Field field : R.id.class.getFields()) {
try {
if(field.getInt(null) == R.id.helloTV) {
Toast.makeText(this, field.getName(), Toast.LENGTH_LONG).show();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
Pros:
No need for manually setting the tag. So you may use the tag for other purposes.
Cons:
Slower due to reflection.
You can use :
String name = ((view != null) && (view.getId() != View.NO_ID)) ? getResources().getResourceEntryName(view.getId()) : "";

android LayoutInflater setText get text from strings + position

I have a viewPager that get its text from the string.xml.
The plan is, depending on the position of ViewPager, it gets the text from strings, for example if the user is in page 3 it should get text from string name="page3".
the important issue is I want to write my code in layoutInflater not in Activity.
here is the code that works just in Activity:
String name = "page" + position;
int id = getResources().getIdentifier(name, "string", getPackageName());
tv.setText(id);
As per your code, you are getting identifier means id of particular string in R.java but not string.
So you can do one thing like this
int[] arr = {R.string.page1,R.string.page2,R.string.page3};
tv.setText(getResources.getString(arr[pos]));

Creating Dynamic R.drawable source and ImageView

I have an Activity which has variable position that comes from another activity. I handle this variable with Intent like below. (Actually position is listView's position from another activity.) and values of position variable are 0 to 200
I took my Extra, then assigned it to a string than I parsed it to an Integer. These are normal and easy for me and working.
Intent i = getIntent();
String position = i.getStringExtra("POSITION");
int position_to_int = Integer.parseInt(position);
But my problem is about resources.
Simply I want to put an image to my LinearLayout dynamically . I have some country flags and they named in format like 0.gif, 1.gif, 2.gif, 3.gif ...
My idea is using position variable's value for this purpose.
but when I try to use position_to_int variable for name of flag, Eclipse returning error normally. Because R.drawble.XXX values storing in R.java
ImageView imageView = new ImageView(this);
// setting image resource
imageView.setImageResource(R.drawable.position_to_int);
How can I use position_to_int variable to show an ImageView dynamically?
You can't access it directly. You'll have to get the resource using its name:
private Drawable getDrawableResourceByName(int name) {
String packageName = getPackageName();
int resId = getResources().getIdentifier("character_you_prefixed" + String.valueOf(name), "drawable", packageName);
return getResources().getDrawable(resId);
}
Note that your resource names must begin with a letter, not a number, or else your project will not compile. Try adding a character to the beginning of each file name.

Android ImageView setImageResource in code

I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
My code (countryCode is the current countryCode in uppercase letters):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can I do this?
One easy way to map that country name that you have to an int to be used in the setImageResource method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
This is how to set an image into ImageView using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
you use that code
ImageView[] ivCard = new ImageView[1];
#override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
you may try this:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));

Categories

Resources