Android : get the id of dynamically generated ImageButton when clicked - android

I have dynamically generated ImageButtons with different ImageResource for each ImageButton. Now I want to know which ImageButton was clicked, how can I determine this ?
Need your help.
Thanks.

you can set an id for each created ImageButton and getId() for check witch button clicked
ImageButton im=new ImageButton(Yourcontext);
im.setId(giveAnID);
//where you check
int theID=im.getId();

In order to do this you could do two things:
Firstly, when dynamically generated the ImageButton you could call setId() in order to set a specific id to this View and store it in List, etc.
Then when you have a click event (or anything else), you can call the getId() method of the View to get the id.
Then you can compare and do anything you want.
Hope this helps!

Any resource is uniquely identified by its id which is generated in R.java file.
So you can use something like :
if(image.getId() == R.id.image) {
// do awesome stuff
}

If your code generates the imageButtons then, in this code you can write something like,
imageButton.setId(1);
and when your imageButton is clicked then you can get it with,
int id = imageButton.getId();

i had to do same thing and this is what i have done
for(int i = 0 ;i<mediaList.size();i++){
view_media_gallery_item = LayoutInflater.from(view.getContext()).inflate(R.layout.e_media_gallery_item, null);
TextView title = (TextView) view_media_gallery_item.findViewById(R.id.media_gallery_item_title);
TextView subtitle = (TextView) view_media_gallery_item.findViewById(R.id.media_gallery_item_subtitle);
ImageView flux_Title_Image =(ImageView) view_media_gallery_item.findViewById(R.id.media_gallery_item_img);
title.setId(i+100);
subtitle.setId(i+1000);
flux_Title_Image.setId(2000+i);
title.setText("" +mediaList.get(i).getTitle());
subtitle.setText(""+mediaList.get(i).getArtist());
System.out.println("view added::::");
view_media_gallery_item.setTag(mediaList.get(i));
view_media_gallery_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("view media clicked");
Media m = (Media )v.getTag();
medialistner.setOnItemclick(m);
}
});

Related

Create an "if statement" or "switch statement" based off a floating action button image resource [duplicate]

I have one ImageView and set a drawable on it. Now I need to get the ID of the drawable on click event of ImageView dynamically. How can I get it?
imgtopcolor = (ImageView) findViewById(R.id.topcolor);
imgtopcolor.setImageResource(R.drawable.dr); // How do I get this back?
Now on touch event of imgtopcolor i want to need drawable id because I am setting different drawable each time and want to compare the drawable with other
I think if I understand correctly this is what you are doing.
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
switch(getDrawableId(imageView)) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
break;
}
});
Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
// See here
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
imageView.setTag(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
imageView.setTag(R.drawable.foo);
break;
}
});
I answered something like this in another question already, but will change it just a little for this one.
Unfortunately, there is no getImageResource() or getDrawableId(). But, I created a simple workaround by using the ImageView tags.
In onCreate():
imageView0 = (ImageView) findViewById(R.id.imageView0);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView0.setTag(R.drawable.apple);
imageView1.setTag(R.drawable.banana);
imageView2.setTag(R.drawable.cereal);
Then, if you like, you can create a simple function to get the drawable id:
private int getDrawableId(ImageView iv) {
return (Integer) iv.getTag();
}
Too easy.
As of today, there is no support on this function. However, I found a little hack on this one.
imageView.setImageResource(R.drawable.ic_star_black_48dp);
imageView.setTag(R.drawable.ic_star_black_48dp);
So if you want to get the ID of the view, just get it's tag.
if (imageView.getTag() != null) {
int resourceID = (int) imageView.getTag();
//
// drawable id.
//
}
Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:
Load a drawable into memory and compare ConstantState or bitmap itself to other one.
Set a tag with drawable id into a view and compare tags when you need
that.
Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.
So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView
If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:
TagViewUtils.getTag(view, ViewTag.IMAGEVIEW_SRC.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_LEFT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_TOP.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_RIGHT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_BOTTOM.id)
TagViewUtils.getTag(view, ViewTag.VIEW_BACKGROUND.id)
TagViewUtils.getTag(view, ViewTag.VIEW_FOREGROUND.id)
The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github.
If you set a drawable in runtime you can use convenient library methods:
setImageViewResource(ImageView view, int id)
In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:
fun ImageView.setImageResourceWithTag(#DrawableRes int id) {
TagViewUtils.setImageViewResource(this, id)
}
You can find additional info in Tagging in runtime
I recently run into the same problem. I solved it by implementing my own ImageView class.
Here is my Kotlin implementation:
class MyImageView(context: Context): ImageView(context) {
private var currentDrawableId: Int? = null
override fun setImageResource(resId: Int) {
super.setImageResource(resId)
currentDrawableId = resId
}
fun getDrawableId() {
return currentDrawableId
}
fun compareCurrentDrawable(toDrawableId: Int?): Boolean {
if (toDrawableId == null || currentDrawableId != toDrawableId) {
return false
}
return true
}
}
A simple solution might be to just store the drawable id in a temporary variable. I'm not sure how practical this would be for your situation but it's definitely a quick fix.
Even easier: just store the R.drawable id in the view's id: use v.setId(). Then get it back with v.getId().

Android get click information object on screen

I have 10 TextView on screen . Now i want get id,string of Textview which i click.
I don't want setOnClickListener for every textview .
Sorry for bad English.
If your TextView are defined in XML then set clickable:"true" and then onClick:"onTextViewClick" to all of your TextViews.
Then in your activity create a method like this:
void onTextViewClick(View view){
int clickedId = view.getId();
}

I have 200 textviews and i want to know which one was pressed then how to change the text

I have a problem... have been thinking about it for a while now and been looking on line and still haven't come up with a clear explanation...
I have a number of textviews and have set onClickListeners to each of them.. and when the user clicks on one of them I want them to have the ability to change the text to another set of string array options which I have created progammatically. When the user selects an option the text should change to the option they choose. (I.e. TextView was A now it is B. hope this makes sense.. anyway... )
The current solution was to set a OnClickListener to every TextView and when someone pressed it an individual dialog showed. But I found that if I do this the code would be so long it would take an eternity to code so am hoping someone has a more elegant way of coding such a long process =(
So I guess my question would be... 1) is there a way I can find out which text view was pressed and then change the text of that TextView being pressed within a single method? to save me having to code 1000 alert dialogs...
http://i.stack.imgur.com/LRJGz.png
I would advise you to use a grid view.
You can see which textview was pressed like this:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
//get id
switch (v.getId()) {
case R.id.textView1: ...
}
});
One of the ways to do what you want is to use the text view setTag() and getTag() methods.
On init of a text view use the setTag() to set some value to identify the view.
In the on click event use the getTag() on the view argument to know which view was clicked.
I would suggest holding the textviews in an array, like so:
TextView[] textViewArray = new TextView[textViewCount];
Then using a for loop assign each one a tag of integer - it's position
textViewArray.setTag(i)
And add an onClickListener to each one, again using a for loop:
textviewArray[i].setOnClickListener(etc...)
Then when one is clicked, you can use get the position of view that was clicked. This will require a custom method inside of your:
textviewArray.setOnClickListener(new customOnClickListener())
Where your customOnClickListner is like this:
private class customOnClickListener implements CompoundButton.{
public void OnClick(View view){
int position = (Integer) view.getTag()
///Do more code here - your processing
}
}
Hope that makes sense :)
For your for loops, you could use for(i = 0, i
Use set id for all text, where set the id positive integer(distinct), and then have one on view click listener(set it all) where u catch all text view clicks(downcast view with textview) and in side it put a switch case where you handle clicks on which text view is clicked.
You have to set "onClickListner" on all of of your textview.
For Saving some length of code i would suggest you create a function of your dialogbox, and give some int parameter to it, which would be directly called by the clickListener of textview,
Like ,
int i=0;
......
textView1 = (TextView)findViewById(R.id.yourtextview1);
textView2 = (TextView)findViewById(R.id.yourtextview2);
......
......
// and so on, for your all textviews
#Override
public void onClick(View view) {
if (view.equals(textView1)) {
i = 1;
CustomDialog(i);
}
//Similarly for all your textViews..
..........
Make A function CustomDialog Like
public void CustomDialog(int i){
if(i==1){
//Do something
}
}

How can I change Text of Textview from other funcion?

this is my first question so I hope to make it clear.
I have one textView with some numerical text and next to it one button with one click listener and what I want is that when you click on the button the numerical value (>=0) of the TextView decrements in one.
Here is part of my code:
TextView Counter = new TextView(this);
if (intSeries != 0)
Counter.setText(Integer.toString(intSeries));
else
Counter.setText("0");
Counter.setId(4);
tablaContador.addView(Counter,Tr);
Button Done = new Button(this);
Done.setText("-1");
if (intSeries != 0)
Done.setVisibility(View.VISIBLE);
else
Done.setVisibility(View.GONE);
Done.setId(6);
Done.setOnClickListener(this);
And this is the onClick funcion (part of it):
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case 6:{
TextView text = (TextView)findViewById(4);
int series = Integer.parseInt(text.getText().toString());
series--;
text.setText(series);
if (series==0){
Button boton = (Button)findViewById(6);
boton.setVisibility(View.GONE);
}
}
}
}
The error is when I try to make the setText inside the onClick function, I hope it can be fixed or maybe recieve other idea to do it.
Thank you so much.
I would avoid all this hardcoding of Ids, use resources instead.
Your call to
text.setText(series)
is passing an int. The only valid setText(int resId) overload expects a resource associated with the int value, i.e. a string resource.
Convert your series value to a string.
Something like:
text.setText(Integer.toString(series));
You should setup series as an integer. And increase/descrease it as you wish. When you want to change the button's text convert the int to String.
Instead of:
text.setText(series);
use:
text.setText(String.valueOf(series));
Variablenames in java can't start with a capital letter. That is reserved for classnames.
Counter -> counter
Done -> done
I tried this and it worked:
//Create onClickListener
OnClickListener pickChoice = new OnClickListener()
{
public void onClick(View v)
{
TextView txt = (TextView) findViewById(4);
int number = Integer.valueOf(txt.getText().toString());
txt.setText(String.valueOf(number -1));
}
};
//Create layout
LinearLayout lnLayout = new LinearLayout(this);
lnLayout.setOrientation(LinearLayout.VERTICAL);
TextView txt = new TextView(this);
txt.setId(4);
txt.setText("0");
lnLayout.addView(txt);
Button Done = new Button(this);
Done.setText("-1");
Done.setId(6);
Done.setOnClickListener(pickChoice);
lnLayout.addView(Done);
setContentView(lnLayout);
Where are you creating your button inside? an activity? the part where you pass the onClickListener to the button doesn't make sense, maybe the button is getting a wrong listener and gets you an error every time you press the button ?
The code should be easy to understand, if there is anything you need me to explain please ask :)

Problems setting the content description to image button

Hello i am trying to set a content description to my button buy when i try to access to it the value that return to me is null.
Here is the code of the button.
//This is the button of the payment.
ImageButton make_pay = new ImageButton(this);
make_pay.setBackgroundResource(R.drawable.add_product);
makePay.addView(make_pay);
makePay.setContentDescription("Precio");
This is the code that i use to access:
make_pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View makepay) {
LinearLayout wrap_area = (LinearLayout)findViewById(R.id.division2);
TextView test = new TextView(FrontActivity.this);
wrap_area.addView(test);
if (makepay.getContentDescription() == null){
test.setText("Precio:1");
}else{
test.setText(makepay.getContentDescription().toString());
}
});
}
You are setting the content description to makePay object (whatever it is, probabbly a ViewGroup). But then, you are setting the listener to the make_pay ImageButton, which is the one received by the listener arguments. Thus, it's content description is not the one assigned to the other object.
Try changing this:
makePay.setContentDescription("Precio");
with this:
make_pay.setContentDescription("Precio");
Anyway, try not to name your objects in such a similar way. It could lead to big confussions.

Categories

Resources