Using the Hello, World Gridview tutorial example, I am attempting to make the image fullscreen on click instead of display the position of the image in the array. As I am unfamilar with Android and this is my first development attempt with it, I'm at a loss. I am familiar with Java though, and I've tried doing things like this (that don't work obviously):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
showImage(v, position);
Toast.makeText(HelloAndroid.this, "" + parent.getId(), Toast.LENGTH_SHORT).show();
}
});
}
private void showImage(View view, int position) {
ImageView imgView = (ImageView) view;
imgView.setImageResource(position);
}
But the app crashes (force close). Any ideas?
Here is the tutorial app I am using
imgView.setImageResource(position);
This gives you an error because you are not using it correctly. The parameter should be pointing to the resource ID of the image (which is an int) e.g. R.id.imageid. Even if you were to supply the right resource ID, what you want to do would not work.
To get the right resource ID, you would need to call the adapter of the view and use the getItemId(position) method to get the correct resource ID. in your ImageAdapter, if you change your getItemId() method to return mThumbsIds[position] rather than 0 (as in Google's example).
However, to achieve your result I would suggest for you to create a new Activity and just load the image like that.
For example:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
long imageId = (ImageAdapter)parent.getAdapter.getItemAt(position);
Intent fullScreenIntent = new Intent(v.getContext(), FullScreenImage.class);
fullScreenIntent.putExtra(thisClassName.class.getName(), imageId);
thisClassName.this.startActivity(fullScreenIntent);
}
});
Assuming you create a full_image.xml layout file, containing just an ImageView with an id of "fullImage", your FullScreenImage class should look like this:
public class FullScreenImage extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.full_image);
Intent intent = getIntent();
long imageId = intent.getExtras().get(thisClassName.class.getName());
ImageView imageView = (ImageView) v.findViewById(R.id.fullImage);
imageView.setLayoutParams( new ViewGroup.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT));
imageView.setImageResource(imageId);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
Something along these lines should work well for you, with some tweaking. Make sure you add FullScreenImage in your AndroidManifest.xml file as an <activity> as well.
Here, you're taking the ID of the view that was clicked (passed in the view argument) and using it to look up itself again:
ImageView imgView = (ImageView) findViewById(view.getId());
That makes no sense, especially since the clicked view apparently has no ID, causing findViewById to return null.
You probably want to pass the ID of your ImageView instead:
ImageView imgView = (ImageView) findViewById(R.id.whatever_the_id_of_the_image_view_is);
Related
EDIT: I've solved this issue, if interested, please take a look at my answer to see how I did it!
I am currently working in Android Studio. I have a ListView that I populate with several items. Within each of these items is an ImageButton that has a "+" as the image. What I want to do is, whenever that image is clicked (not the entire ListView item, just the image), I want that image of "+" to become another image. Any help would be appreciated, as this has been an ongoing issue for a while!
Here is the current code that I attempt to use to achieve this:
final ImageButton movieSeen = (ImageButton convertView.findViewById(R.id.movieWatched);
movieSeen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movieSeen.setImageResource(R.drawable.ic_check_circle_black_24dp);
}
});
Currently this does update the image that I click correctly, BUT it also updates images that are not yet rendered on the screen, so when I scroll the list view down, other objects are also changed to ic_check_circle_black_24dp.
What I want is pretty straightforward, I just don't know how to achieve it. I just want to click an ImageButton, that's inside an item on a ListView, and have that ImageButton change its image resource.
Here is my custom array adapter as requested!
private class MovieScrollAdapter extends ArrayAdapter<Movie> {//custom array adapter
private Context context;
private List<Movie> movies;
public MovieScrollAdapter(Context context, List<Movie> movies){
super(context, -1, movies);
this.context = context;
this.movies = movies;
if(this.movies.isEmpty()){//if no results were returned after all processing, display a toast letting the user know
Toast.makeText(getApplicationContext(), R.string.no_matches, Toast.LENGTH_SHORT).show();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.movie_layout, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.title);
title.setText(movies.get(position).getTitle());
TextView plot = (TextView) convertView.findViewById(R.id.plot);
plot.setText(movies.get(position).getPlot());
TextView genre = (TextView) convertView.findViewById(R.id.genre);
genre.setText(movies.get(position).getGenre());
TextView metaScore = (TextView) convertView.findViewById(R.id.metascore);
if(movies.get(position).getMetaScore() == -1){//if the metaScore is set to -1, that means movie has not been rated, which by inference means it is not yet released
metaScore.setText(R.string.movie_not_released);
metaScore.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9.5f);//smaller text so it fits without breaking anything
metaScore.setTextColor(getColor(R.color.colorAccent));
} else {
metaScore.setText(" " + Integer.valueOf(movies.get(position).getMetaScore()).toString() + " ");//using white space for minor formatting, instead of altering margins each time this is rendered
metaScore.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
//setting up a "highlighted" background to achieve metacritic square effect
Spannable spanText = Spannable.Factory.getInstance().newSpannable(metaScore.getText());
spanText.setSpan(new BackgroundColorSpan(getColor(R.color.metaScore)), 3, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
metaScore.setText(spanText);
metaScore.setTextColor(getColor(android.R.color.primary_text_dark));
}
ImageView image = (ImageView) convertView.findViewById(R.id.imageView);
new ImageDownloadTask((ImageView)image).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, movies.get(position).getPosterURL());//because there are several images to load here, we let these threads run parallel
title.setOnClickListener(new View.OnClickListener() {//setting up a simple onClickListener that will open a link leading to more info about the movie in question!
#Override
public void onClick(View v) {
Uri uri = Uri.parse(movies.get(position).getMovieURL());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final ImageButton movieSeen = (ImageButton) convertView.findViewById(R.id.movieWatched);
movieSeen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movieSeen.setImageResource(R.drawable.ic_check_circle_black_24dp);
}
});
return convertView;
}
}
The problem is on a ListView, the views are being reused to save memory and avoid creating a lot of views, so when you change a view it keeps the state while it's being reused to show another item.
For example, you have 100 elements, you touch the first element ImageButton and that button is changed. Maybe on the screen there are 5 elements of the list showing, and you changed the first one. But if you scroll to the element number 15 the system is not creating 15 views, is taking the first one you clicked before and is changing the content.
So, you are expecting to have a view with a "+" ImageButton icon but you see another icon, that's because you must keep the view state inside a model object and set the state every time 'getView' is called.
Post your list adapter to see how is implemented.
UPDATE:
Now I see your adapter implementation I suggest you to add an int field inside Movie class to save the resource id you want to show on the ImageButton. Then inside the onClickListener you must set to this field the resource you want to show on the view when its clicked, and call notifyDataSetChanged(). After that you must do inside getView():
movieSeen.setImageResource(movies.get(position).getButtonImageResource());
Use RecyclerView and set the OnItemClickListener on your ImageButton within your view holder.
This already answered question should help.
The adapted code below is coming from this nice tutorial. Using ReciclerView with an adapter like this will solve your concern.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> mDataset;
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public TextView txtHeader;
public ViewHolder(View v) {
super(v);
txtHeader = (TextView) v.findViewById(R.id.xxx);
imageView = (ImageView) v.findViewById(R.id.yyy);
}
}
public MyAdapter(ArrayList<String> myDataset) {
mDataset = myDataset;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final String name = mDataset.get(position);
holder.txtHeader.setText(mDataset.get(position));
holder.imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do here what you need to change the image content
}
});
holder.itemView.setBackground(....); // Initialize your image content here...
}
//...
}
Here is my suggestion to achieve what you want :
Create An Interface in your adapter :
public interface YourInterface{
void selectedImage(int position,ImageView iamgeView);
}
Create variable interface in your adapter that you just created :
private YourInterface yourInterface;
and make your adapter constructor like this :
public YourAdapterConstructor(YourInterface yourInterface){
this.yourInterface = yourInterface;
}
in your ImageView onClickListener :
final ImageButton movieSeen = (ImageButton) convertView.findViewById(R.id.movieWatched);
movieSeen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourInterface.selectedImage(position, imageView);
}
});
and then finally in your class activity, Implements YourInterface and change you ImageView there :
#Override
public void selectedImage(final int position,final ImageView imageView) {
//change your image view here
}
I'd like to thank everyone for their support. Unfortunately, with the way my code is written (rather messily and without much regard for what my professors taught me), I was unable to get most of these solutions to work. I did however, find a solution that falls in line with my own framework that I've had going into this. Unfortunately I could not redo my entire adapter method, or implement various interfaces that would cause me to have to rewrite a huge chunk of code for something seemingly trivial.
So, if anyone finds themselves in this situation in the future, here is my solution:
In the Movie class, I add a boolean value that represents my values, along with some getters and setters:
private boolean watchedStatus;
public boolean hasSeen() {return watchedStatus;}
public void toggleWatchedStatus(){
watchedStatus = !watchedStatus;
}
In the getView method, I simply get a reference to the ImageButton, and then based on the boolean value returned by "hasSeen," I set the ImageResource to one of two states:
#Override
public View getView(final int position, View convertView, ViewGroup parent){
ImageButton movieSeen = (ImageButton) convertView.findViewById(R.id.movieSeen);
if(movies.get(position).hasSeen()){
movieSeen.setImageResource(R.drawable.ic_check_circle_black_24dp);
} else {
movieSeen.setImageResource(R.drawable.ic_add_circle_black_24dp);
}
}
Next, I override the OnClickListener, and make it so that whenever the button is clicked, the boolean value in the Movie.java class is toggled. The key here was using the ArrayAdapter's method "notifyDataSetChanged()" This completes the process, and lets the ListView know that it should update itself:
final ImageButton movieSeenForClick = (ImageButton) convertView.findViewById(R.id.movieSeen);
movieSeen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//movieSeenForClick.setImageResource(R.drawable.ic_check_circle_black_24dp);
movies.get(position).toggleWatchedStatus();
System.out.println(movies.get(position).hasSeen() + " ------- position: " + position);
notifyDataSetChanged();
}
});
Thanks again for the time taken to provide information, a lot of it really did steer me int he right direction, I just had to use the information correctly with the way my code was structured.
I need to show an image in full screen, on clicking of View Pager in android.
I have tried this.
view.myPager.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e("VIEW PAGER", "VIEW PAGER");
Toast.makeText(activity, "ZOOM", Toast.LENGTH_SHORT).show();
}
});*
Suggestion appreciated.
Thanks
Set the listener on the image inside instantiateItem():
#Override
public Object instantiateItem(View collection, int position) {
final LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.my_layout, null);
final ImageView image = (ImageView)layout.findViewById(R.id.image_display);
final int cPos = position;
image.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
ImageView i = (ImageView)v;
if(cPos == 0)
{
//...
}
//...
}
});
return layout;
}
Alternatively, you could use the ImageView.setTag() method to include data about what Activity to launch. e.g.
if(position == 0) image.setTag("com.blah.android.SomeActivity");
if(position == 1) image.setTag("com.blah.android.AnotherActivity");
//...
And the inside the onClick() above have this instead:
ImageView i = (ImageView)v;
String activityClassName = (String)i.getTag(); // Get the info we stored in the tag.
MyActivity.this.startActivity((new Intent()).setClassName(MyActivity.this, activityClassName));
Note that here you don't actually need the cast to ImageView, since getTag() is a method of View. You also don't need a separate OnClickListener for each ImageView. You could just create a single instance of an OnClickListener that grabs the tag data as above, and launches the appropriate activity. Set this OnClickListener on every ImageView inside instantiateItem().
P.S. I strongly recommend, if you are downloading images, that you look at some of the image downloaders that have been written for Android. e.g.
https://github.com/nostra13/Android-Universal-Image-Loader
You cannot click on a ViewPager, as a ViewPager manages a UI, but does not have its own UI.
You will need to add appropriate listeners (e.g., OnClickListener) to widgets inside pages in the ViewPager, just as you would for an app that did not have a ViewPager.
I've implemented a gridview of images that are picked from sdcard.Now i want every image to be shown in dialog on click.How to do it within Image Adapter?Any help will be appreciated.Thanks in advance.
You wouldn't do that in your adapter... Do it inside your click listener (from wherever you call and set the gridview adapter).
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageView iv = (ImageView) v.findViewById(R.id.imageviewid); // get the resource id
Drawable image = iv.getDrawable(); // get the image
CreateYourDialog(image); // pass the image to a method to create your dialog
}
});
If your GridView is only the imageview for each cell, then you can skip the findViewById line of code and simply use Drawable image = v.getDrawable();.
I have got an activity that shows a grid view with different images. When clicking on one of those images I want the clicked image to be the background image of another activity.
How can I do that?
This is my activity that shows the grid view:
public class HelloGridViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView) findViewById(R.id.gridview);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//WHAT SHALL I PUT HERE????
}
}
}
So, the poster didn't (originally) specify exactly whether the other activity was to be opened immediately on click, or if the clicked item's image just needed to be recorded for use later. The first problem seems more common to me, as in a GridView that shows a set of image thumbnails. The user clicks on that, and a new Activity showing just that item's information comes up. That thumbnail image maybe goes full screen. Anyway, maybe that's not what the poster had in mind, but that's my assumption (and probably somebody will eventually find this answer with such a use case in mind).
It also isn't specified how the images are stored, so I'll make assumptions that
The ImageAdapter's images are bundled resources of this app
We can make some changes to the ImageAdapter, to store some data to solve this problem
So, with that, I take a standard ImageAdapter, and add one line of code to record the integer resource ID for each ImageView, in the ImageView's tag property. There's many ways to do this, but this is the way I chose.
public class ImageAdapter extends BaseAdapter {
/* see code removed at
http://developer.android.com/resources/tutorials/views/hello-gridview.html
*/
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
// here we record the resource id of the image, for easy access later
imageView.setTag(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5
};
}
Then, when the Hello activity has a grid item clicked, I retrieve the image's resource id and pass it as an Intent extra (HelloGridViewActivity.java):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView) findViewById(R.id.gridview);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
final Context activity = this;
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Object tag = v.getTag();
if (tag instanceof Integer) {
// we stored a reference to the thumbnail image in the ImageView's tag property
Intent i = new Intent(activity, AnotherActivity.class);
Integer resourceId = (Integer)tag;
i.putExtra("backgroundImage", resourceId);
startActivity(i);
}
}
});
}
And finally, when the new activity (AnotherActivity) is opened, we retrieve that intent extra, and decode it as an integer resource id, and set it as the background image with a fullscreen ImageView (AnotherActivity.java):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.another);
Intent i = getIntent();
//String bgImage = i.getExtras().getString("backgroundImage");
int resId = i.getExtras().getInt("backgroundImage");
try {
ImageView background = (ImageView) findViewById(R.id.bgImage);
// Another alternative, if the intent extra stored the resource 'name',
// and not the integer resource id
//Class<?> c = R.drawable.class;
//background.setImageResource(c.getDeclaredField(bgImage).getInt(c));
background.setImageResource(resId);
} catch (Exception e) {
e.printStackTrace();
}
}
I also show above some commented out code, if for some reason you need to pass a string name of an image resource, instead of an integer resource code. The commented out code looks up the resource id for the given image name. According to the resource names used in my ImageAdapter, a sample string name to pass might be "pic1". If you do this, of course, the calling Activity (HelloGridViewActivity) needs to encode the Intent extra as a String, not an integer.
Get the resource ID of the image you want as the BG and save it to preferences.
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
saveImageId(position);
}
private void saveImageId(int position) {
int id = getImageId(); // get the R.drawable.* id of the image. You should be able to figure this out.
Editor ed = PreferenceManager.getDefaultSharedPreferences(this).edit();
ed.putInt("bg_image_id", id);
ed.commit();
}
Now in your other activity, you can get the image id:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int id = prefs.getInt("bg_image_id", R.drawable.default_background); //Get image id, use default background if there isn't one.
LinearLayout mLayout = (LinearLayout) findViewById(R.id.background_layout);
mLayout.setBackgroundResource(id);
Good luck
I have a GridView with a bunch of icons and I need to select one. And by select I mean:
I need the drawable id to store into a database (so I can access it later)
I need to draw some kind of visual cue on the grid to let the user know which icon is currently selected
I found this:
http://groups.google.com/group/android-developers/browse_thread/thread/f08a58167dbaa8c8
So I guess setSelection is out of the picture and I can't use it to select the icon itself nor draw the visual cue. I know the grid item position in the onItemClickListener and I can save it as a private class variable. My biggest problem is drawing that visual cue.
How can I achieve that? How can I draw a visual cue on the clicked item and if the user clicks different items, to "undraw" that visual cue and redraw it in the new item?
After tackling with this for a couple of hours I think I finally found the solution I was looking for. Although the answers are barely related, the initial edits on Ian solution helped me find this solution :)
I'm not going to explain everything I did, I think it's pretty self explanatory. Just a few remarks:
First I tried view.Invalidate() and view.postInvalidate() instead of iconAdapter.notifyDataSetChanged() but neither worked. The documentation stated that the invalidate methods only "asked" to redraw the view "when possible".
I was looking for a simpler solution than to merge two drawables. For instance, draw the icon on the ImageView background and the visual cue as the image. For some strange reason, the visual cue started to show randomly all over the other icons when the GridView was scrolled. I don't understand why, but the idea of a visual cue on top of a background image makes perfect sense to me and ImageView allows that, no need for that extra merge method. However, I couldn't make it work without it...
MyActivity.java
public class MyActivity extends Activity {
private GridView mGridViewIcon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGridViewIcon = (GridView)findViewById(R.id.gridview_icon);
mGridViewIcon.setAdapter(new IconAdapter(this));
mGridViewIcon.setOnItemClickListener(new GridView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
IconAdapter iconAdapter = (IconAdapter)parent.getAdapter();
iconAdapter.setSelectedItemPosition(position);
iconAdapter.notifyDataSetChanged();
}
});
}
}
IconAdapter.java
public class IconAdapter extends BaseAdapter {
private int mSelectedPosition;
private Integer[] mThumbIds;
private int mIconSize;
private Context mContext;
public IconAdapter(Context context) {
mThumbIds = AppHelper.ICON_SET.keySet().iterator().next();
mIconSize = context.getResources().getDimensionPixelSize(R.dimen.default_icon_size);
mContext = context;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mContext.getResources().getDrawable(mThumbIds[position]);
}
#Override
public long getItemId(int position) {
return mThumbIds[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize));
} else {
imageView = (ImageView)convertView;
}
if(mSelectedPosition == position) {
imageView.setImageDrawable(mergeDrawableLayers(mThumbIds[position],
R.drawable.ic_note_selected_mark));
} else {
imageView.setImageResource(mThumbIds[position]);
}
return imageView;
}
public void setSelectedItemPosition(int position) {
mSelectedPosition = position;
}
private Drawable mergeDrawableLayers(int background, int overlay) {
Drawable[] drawableLayers = new Drawable[2];
drawableLayers[0] = mContext.getResources().getDrawable(background);
drawableLayers[1] = mContext.getResources().getDrawable(overlay);
return new LayerDrawable(drawableLayers);
}
}
I believe, that if you want some kind of selection cue, you need a focusable object. However, with a focusable object (such as a Button), attaching OnItemClickListener to the GridView does not work (if i remember correctly). Rather, you must individually attach an OnClickListener to each item at getView() in the adapter.
Adapter:
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
Button button;
if (convertView == null) { // if it's not recycled, initialize some attributes
button = new Button(mContext);
// set layout params (make sure its GridView.layoutParams)
// and other stuff
}
else {
button = (Button) convertView;
}
button.setBackgroundResource(mThumbIds[position]); // mThumbIds hold Resource Ids
button.setOnClickListener(new OnClickListener() {
onClick(View v) {
// store directly to database here, or send it with the activity with sharedPreferences (below)
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("button_id", mThumbIds[position]);
// Commit the edits!
editor.commit();
}
});
return button;
}
}
On Activity Side, save button onClickListener:
onClick(View v) {
// Restore preferences
SharedPreferences settings = getSharedPreferences("MY_PREFERENCE", 0);
int id = settings.getInt("button_id", -1);
// now safe all stuff to database
}
There may be details missing because a Button is focusable, but i think this should do. Also , you will achieve the selection by using a .xml defined selector resource. That, however, should be addressed in a separate question.
Edit 1:
Actually now that i think about it, i'm not sure if a drawable .xml (the selector) can have an ID. I'll have to implement this at home later on and try it.
Edit 2:
I added the sharedPreference part
Edit 3:
Added activity side querying of sharedPreference.