How to perform click event on View Pager in android - android

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.

Related

How to change an image in a ListView, when the image is clicked?

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.

How to efficiently click items with a listview

I have a list view and in each list item i have for image views and three text view, three of these image view are to act like an image button i.e respond to on click events and so are two of the text view. I have tried using ItemOnClickListeneri mean like this
#Override
public void onItemClick(AdapterView<?> arg0, View convertView, int pos,
long arg3) {
// TODO Auto-generated method stub
bomb = (ImageView) convertView.findViewById(R.id.bomb);
Log.i("Item Clicked", "Item was clicked at pos" + position);
bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Perform action on click
//Run what ever task neccessary
}
});
}
But this has a problem it only responds on the second click. i know it has something to do with the parent and child focus but i haven't been able to get around that.
I also tried using the
static class View Holder except i got the implementation wrong it does not respond at all even after two clicks.
Also am using a custom adapter, i used to do it directly from the getView overide method but i found out the hard way that is isn't the best ways to implement what i want to do.
Please i need something that would work for me cause i tried a coupleof thing other than the above mentioned but they have failed.
Get View Codes
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
pos = position;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.singlepost, parent, false);
holder = new ViewHolder();
holder.bomb = (ImageView) convertView.findViewById(R.id.bomb);
holder.bomb.setOnClickListener(bomb_listener);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
holder.bomb.setOnClickListener(bomb_listener);
}
return convertView;
}
private OnClickListener bomb_listener = new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("HOMEADAPTER", "BOOMB WAS CLICKED AT POSITON" + pos);
holder.bomb.setImageResource(R.drawable.redheart);
}
};
static class ViewHolder {
TextView reporter;
TextView shell;
TextView sheller;
TextView likesnum;
TextView favsnum;
TextView comnum;
ImageView bomb;
ImageView star;
ImageView comment;
}
With this new getview implementation i still don't get the exact item i intend to click
Add the clicklistener code block inside getView() i.e where you create the view,
getView(...) {
if (view == null) {
viewHolder = new ViewHolder();
view = ...inflateView code...
View bomb = view.findViewById(R.id.bomb);
bomb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Perform action on click
//Run what ever task neccessary
}
});
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)view.getTag();
}
}
Views respond to events in a bottom-up fashion. Meaning events start with the child view and are passed up to the parent views. If a view cannot or does not respond to an event, it is passed up the chain. When you first click an image, the image view has no OnClickListener associated with it, and therefore cannot respond to the event. On that first click though, you are setting a listener to it. So the next time you click that image, it now has a listener and can respond to the event. This is why it is not responding as expected on the first click. As 66CLSjY suggested, you probably want to override getView (int position, View convertView, ViewGroup parent) in your list adapter to set the listener when the image is added to the list instead of when you click on it.
In response to your comment on 66's answer, keep in mind that ListViews reuse views as much as possible. So even if convertView is not null, you still need to either set a new OnClickListener to it or account for the reuse in some way or it will basically be like you clicked a different image.
After complaining about this issue and trying to get a work around it. Personally i think androids API of the list view is terrible and should be improved upon so that it is easy to use and implement. I think its a bad idea to call your listeners in the override get view method cause you can't always trust the android system to return to you the exact view in which you are requesting due to performance reasons. I am quoting for the developers of the list view. using the View Holder static class only helps to hold the views and access them faster but it doesn't assist in handling event listeners for specific items view within the list view item and honestly i haven't seen any reasonable solution on the internet or Google developer site.
Okay after two nights of racking my brains and endless testing i finally have a solution.
Using the setTagand the ViewHolder implementation but only differently, turn your ViewHolder static implementation into a View what i mean is this
static class ViewHolder extends View implements OnClickListener {
public ViewHolder(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
ImageView bomb;
public void assignList(){
if(bomb != null)
bomb.setOnClickListener(this);
}
public int position = -1;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("HOMEADAPTER", "OUR OWN STUFF");
}
}
Once you have done that in your activity where you implement your OnItemClickListener
all you need to do is get the tag you set like so
ViewHolder holder = (ViewHolder) view.getTag();
and thats all baby! you are 90% done the final 10% thing you need to do is what ever you wish to do with your gotten view.

How to change list item data when clicked on a sub view

holder.voteUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = myList.getPositionForView((View) v
.getParent());
final ListItem li = values.get(position);
li.voteUp_value = true;
//In getView(), I set different image to holder.voteUp ImageView depending on this value.
//Hence I call notifyDataSetChanged(); which takes care of it.
notifyDataSetChanged();
}
});
But the problem is, Since the whole list is notified, it flickers every time I vote.
I cannot changed the Image of the holder.voteUp directly, because there is a holder.voteDown which has to be changed too, depending on the li.voteUp_value. So, I went with notifyDataSetChanged(); which takes care of all this.
Is there a way I can get the Views from parent View and set the Images, instead of notifyDataSetChanged();?
like:
ViewParent vp = v.getParent();
ImageView im = vp.findViewById(R.id.voteUp);
im.setImageResource.....
But there is nothing like findViewById for ViewParent
You should be able to use the view passed to you from the onClick() listener. Just changing the image should be enough to make it redraw, but if not you can still tell it to manually.
#Override
public void onClick(View v) {
final int position = myList.getPositionForView((View) v
.getParent());
final ListItem li = values.get(position);
li.voteUp_value = true;
ImageView im = vp.findViewById(R.id.voteUp);
if ( im != null ) {
//Update the view here
}
}

Why does ImageView.setAlpha() set alpha to multiple ImageViews in a GridView?

I'm implementing a custom gallery that allows multiple photo selection.
I'm using a GridView with a simple ImageAdapter class extended from BaseAdapter.
Here is my ImageAdapter class:
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageview.setId(position);
holder.imageview.setLongClickable(true);
holder.imageview.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View arg0) {
int id = arg0.getId();
ImageView img = (ImageView) arg0;
if (thumbnailsselection[id]) {
Log.d("PRTAG", "deselecting img with id: " + img.getId());
img.setBackgroundResource(R.drawable.imgview_noborder);
img.setAlpha(255);
thumbnailsselection[id] = false;
} else {
Log.d("PRTAG", "selecting img with id: " + img.getId());
img.setAlpha(128);
img.setBackgroundResource(R.drawable.imgview_border);
thumbnailsselection[id] = true;
}
return true;
}
});
holder.imageview.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int id = v.getId();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + arrPath[id]),
"image/*");
startActivity(intent);
}
});
holder.imageview.setImageBitmap(thumbnails[position]);
holder.id = position;
return convertView;
}
}
All images are added correctly, the onClick() method works fine (it opens up the correct image).
The problem is with onLongClick(). I'm adding a custom background and setting the alpha (128 - image selected, 255 - image not selected) on the image that is long clicked on. The actual selection works fine, it selects the right images.
The actual problem is that the background and alpha are set to multiple (random) images when scrolling the grid view.
Has anyone experienced something like this? Any thoughts on what could be causing this?
Thanks.
Your views are reusable, it means that you need to update alpha every time getView is invoked. Not only on LongPress
Create ArrayList selectedImages ivar for all selected images.
- onLongPress add/remove image to selectedImages
- In your getView method check if image is stored in a list and set according alpha value
You need to get familiar with ListView views reusage concept. Basically GridView reuses views while scrolling. So if You change some view, then it obviously will be changed then reused (until You're not changing the property of it in getView()). Checkout Google I/O video with more explanation about ListView, because most of it applies to GridView also.
So, if You need to have some views with different properties, then You have 2 options:
Make views of another type (in other words use getItemViewType() and getItemViewTypeCount() and change types dynamically with calling notifyDataSetChanged());
Store specific items positions (or some kind of flags in ViewHolder, in Your case it might be thumbnailsselection array information) and setup view property every getView() call using stored before information;
I suggest not to use ImageView's click and long click listeners in getView() method, but to use ListView's or GridView's setOnItemLongClickListener and setOnItemClickListener.
In these listeners you should just save the state of an item, selected or not, and in getView() method you should look-up the item's state and do the following:
if (thumbnailsselection[id]) {
Log.d("PRTAG", "deselecting img with id: " + img.getId());
img.setBackgroundResource(R.drawable.imgview_noborder);
img.setAlpha(255);
} else {
Log.d("PRTAG", "selecting img with id: " + img.getId());
img.setAlpha(128);
img.setBackgroundResource(R.drawable.imgview_border);
}
Basically, in every getView() call you should verify your data object state and always adjust the view's state before returning it.

How to set a background drawable on a clicked GridView item in Android?

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.

Categories

Resources