How to disable a Gallery's item? - android

I have a gallery where I have implement a custom adapter extending the BaseAdapter. For some items, I want them to be disabled, and not clickable as well.
Overriding the isEnabled(int) method doesn't work. I am still able to click on the disabled items, and then, the gallery centers this item inside it.
Any ideas?

This following is the relevant source code of gallery widget
public boolean onSingleTapUp(MotionEvent e) {
if (mDownTouchPosition >= 0) {
// An item tap should make it selected, so scroll to this child.
scrollToChild(mDownTouchPosition - mFirstPosition);
// Also pass the click so the client knows, if it wants to.
if (mShouldCallbackOnUnselectedItemClick || mDownTouchPosition == mSelectedPosition) {
performItemClick(mDownTouchView, mDownTouchPosition, mAdapter
.getItemId(mDownTouchPosition));
}
return true;
}
return false;
}
As you can see, the gallery scrolls to the tapped child item before performing the click on it.
So the only way you can truly disable an item is by extending Gallery and overriding onSingleTapUp(MotionEvent e) in it.
#Override
public boolean onSingleTapUp(MotionEvent e) {
int itemPosition = pointToPosition((int) e.getX(), (int) e.getY());
if (item at itemPosition is disabled) {
// Do nothing.
return true;
}
return super.onSingleTapUp(e);
}
Try and let me know.

Try the below code where you can handle the click event for specific positions. Also you can disable the specific items.
public class SplashActivity extends Activity{
private Activity _activity;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Gallery g = new Gallery(this);
g.setAdapter(new ImageAdapter(this));
setContentView(g);
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4,
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4
};
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
if(position!=0){
i.setEnabled(false);
i.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(SplashActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
return i;
}
}
}

Related

Select multiple items in GridView

I am developing a gallery-like Activity. Everything runs fine but there is a key functionality which is missing and I couldn't find a decent answer or explanation. What I need is to give the user the ability to select multiple items by long clicking on them.
Here is the desired result:
You can clearly see the selected pics and the options in the ActionBar.
My setup is this:
1.I have a GridView in my XML:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth"
android:gravity="center"/>
2.It is attached to a class, which extends BaseAdapter and loads images using Picasso:
public class GalleryAdapter extends BaseAdapter {
Context mContext;
List<String> mDataset;
public GalleryAdapter(Context context, List<String> dataset) {
mContext = context;
mDataset = dataset;
}
#Override
public int getCount() {
return mDataset.size();
}
#Override
public Object getItem(int position) {
return mDataset.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200,200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
} else {
imageView = (ImageView) convertView;
}
//TODO: REMOVE INTEGER.VALUEOFF. IT'S MADE FOR MOCK
Picasso.with(mContext).load(Integer.valueOf(mDataset.get(position))).fit().into(imageView);
return imageView;
}
}
3.It is attached to the Activity:
//Get images paths
List<String> data = getImagesPath(this);
List<String> sortedData = new ArrayList<>();
for(String file : data){
sortedData.add(0, file);
}
GalleryAdapter adapter = new GalleryAdapter(this, sortedData);
mGallery.setAdapter(adapter);
From now on the struggle begins:
I tried making my item in the GridView to implement Checkable:
public class CheckableItem extends LinearLayout implements Checkable{
private boolean mIsChecked = false;
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
public CheckableItem(Context context) {
super(context);
}
#Override
protected int[] onCreateDrawableState(int extraSpace) {
int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked())
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
return drawableState;
}
#Override
public void setChecked(boolean checked) {
mIsChecked = checked;
refreshDrawableState();
}
#Override
public boolean isChecked() {
return mIsChecked;
}
#Override
public void toggle() {
setChecked(!isChecked());
refreshDrawableState();
}
Then I load it in my XML and added .setChoiceMode(GridView.CHOICE_MODE_MULTIPLE) to my GridView in the Activity. Nothing Happened.
Added MultiChoiceModeListener:
class MultiChoiceListener implements GridView.MultiChoiceModeListener{
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
int selectCount = mGallery.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
Then added it to my gridView .setMultiChoiceModeListener(newMultiChoiceListener()); but still no results.
Can someone propose a way to achieve this item selecting behavior in GridView? I'd like to use the native Android API, no 3rd party libraries.
I think Checkable and the rest that I see in your code is a bit of an overkill...When I want to implement something like that I just add another field in the class of the object that is shown in the GridView/ListView which stores the checked state of the object. example:
class Image {
Bitmap bm;
boolean isChecked=false;
public Image(Bitmap bm){
this.bm=bm;
}
public boolean isChecked(){
return isChecked;
}
public void toggleChecked(){
isChecked = !isChecked;
}
}
and feed an ArrayList to the adapter. an in the getView method of the adapter I do something like this;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(images.get(position).isChecked()){
//show the overlay view that suggests the item is selected
}
else{
//hide the overlay view
}
}
finally in the onItemClickListener of the ListView
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
images.get(position).toggleChecked();
listView.getAdapter().notifyDataSetChanged();
}
});

How to flip each GridView cell on touch and show another image?

In my app i need to perform flip animation on cells of Grid View to show another image when user touches. initially i have populated grid view with images when user touches them they should flip and some other image is shown to user.Thanks in advance.
this is my adapter class:-
public class Adapter extends BaseAdapter {
private Context mycontext;
public Integer[] picids = {
R.drawable.pic_1, R.drawable.pic_2, R.drawable.pic_3,
R.drawable.pic_4, R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8, R.drawable.pic_9
};
public Adapter(Context c){
mycontext = c; }
#Override
public int getCount() {
// TODO Auto-generated method stub
return picids.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return picids[position];
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview = new ImageView(mycontext);
imageview.setImageResource(picids[position]);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setLayoutParams(new GridView.LayoutParams(120,120));
return imageview ;
}
}
and following is my main activity class:-
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView grid = (GridView)findViewById(R.id.grid_view);
grid.setAdapter(new Adapter(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
A relatively hacky way to do this would be to use JazzyListView, and "grab" an animation out of the source and implement it in your onClick listener to trigger an animation event.

Android viewflipper and gallery

I am trying to develop a application which contain a gallery with view flipper.
Gallery shows all the images.What I want to do is, the image which is shown in the view flipper should be highlighted in the gallery.
Currently I am able to highlight it on onClick.But not able to make communication between both.
I tried using following method
viewflipper.getDisplayedChild();
but it doesn't work.
following is my code
public class SliderActivity extends Activity
{
int mFlipping = 0 ;
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;
android.widget.ViewFlipper flipper;
Gallery gallery;
private int[] IMAGE_IDS =
{
R.drawable.android0, R.drawable.android1, R.drawable.android2,R.drawable.android3,R.drawable.android4
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mygame);
flipper = (android.widget.ViewFlipper) findViewById(R.id.flipper1);
for(int i=0;i<IMAGE_IDS.length;i++)
{
// This will create dynamic image view and add them to ViewFlipper
ImageView image = new ImageView(getApplicationContext());
image.setBackgroundResource(IMAGE_IDS[i]);
flipper.addView(image);
}
gallery=(Gallery)findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
if(mFlipping==0){
/** Start Flipping */
flipper.startFlipping();
mFlipping=1;
//mButton.setText(R.string.str_btn_stop);
}
else{
/** Stop Flipping */
flipper.stopFlipping();
mFlipping=0;
// mButton.setText(R.string.str_btn_start);
}
}
public class ImageAdapter extends BaseAdapter
{
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.Theme);
mGalleryItemBackground = a.getResourceId(
R.styleable.Theme_android_galleryItemBackground,0);
a.recycle();
}
public int getCount()
{
return IMAGE_IDS.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position,View convertView, ViewGroup parent)
{
ImageView i = new ImageView(mContext);
i.setImageResource(IMAGE_IDS[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
public void onClick(View v) {
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
If I understand your question... I think you need to use setOnItemSelectedListener...
gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View gallery,
int position, long arg3) {
myPosition = position;
//tell your flipper something useful here using the current position of the gallery
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
And talk to your flipper from in the onItemSelected callback.

Focus issue in gridview

I have a gridview in my layout. I have added three imageviews to this gridview.
I have the following requirement. By default when I launch or resume the activity, I need to have an imageview selected by default. How can I accomplish that? Placing gridView.setSelection(1); in onResume() have no effect ie; the imageview does not get selected on launching or resume, I wonder why! Can someone please let me know why this does not get highlighted?
Following is my main activity and adapter class.
public class MyActivity extends Activity
{
GridView gridView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
// set up the onClick listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Log.d("Pos", "setOnItemClickListener() - pos:" + position);
handleItemClick(position);
}
});
}
public void onResume() {
super.onResume();
gridView.setSelection(1);
}
private void handleItemClick(int position) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
switch(position) {
case 0: // Phone
intent.setClassName("com.android.contacts",
"com.android.contacts.DialtactsActivity");
break;
case 1: // People
intent.setClassName("com.android.contacts",
"com.android.contacts.activities.PeopleActivity");
intent.setAction("com.android.contacts.action.LIST_CONTACTS");
break;
case 2: // Places
intent.setClassName("com.android.contacts",
"com.android.contacts.DialtactsActivity");
break;
default:
break;
}
startActivity(intent);
}
}
Adapter class
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in an array
public Integer[] mThumbIds = {
R.drawable.call,
R.drawable.contacts,
R.drawable.music,
};
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 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(350, 350));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
imageView.setId(position);
return imageView;
}
}
You can try this:
public void onResume() {
super.onResume();
Thread.sleep(1);
gridview.requestFocusFromTouch();
gridview.setSelection(1);
}
or also this can help:
public void onResume() {
super.onResume();
mGridView.setSelection(1);
mGridView.requestFocusFromTouch();
mGridView.setSelection(1);
}
Just a guess may work
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
gridView.setSelection(1); <--- try to add this here

How can I change Image on Gridview Runtime?

I have one GridView with 3 Column and 3 Rows I want to change Image when User Click any two Images.
for Example I Click First Row 1 and Column 3 Image and Secondly I Click on Row 3 and Column 2 show now i want to change this two Images like Swap the Image How is it Possible ?
public class MainActivity extends Activity {
/** Called when the activity is first created. */
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridviewmy);
gridView.setAdapter(new ImageAdapter(this));
final ImageAdapter im = new ImageAdapter(this);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int i=0; int j=0;
if( i != 0){
j=arg2;
System.out.println("First Click "+j);
}else{
i=arg2;
System.out.println("Second Click "+i);
}
im.getItem(arg2);
//im.changeImage();
Toast.makeText(MainActivity.this, ""+arg2, Toast.LENGTH_SHORT).show();
System.out.println("AdapterView "+arg0);
System.out.println("View "+arg1);
System.out.println("Integer "+arg2);
System.out.println("long "+arg3);
}
});
}
}
class ImageAdapter extends BaseAdapter{
private Context mContext;
ImageView iView;
public ImageAdapter(Context c){
this.mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
System.out.println("Item Is :-"+mThumbIds[position].toString());
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
System.out.println("Geting Id of Item "+mThumbIds[position]);
if(iView != null){
iView.setImageResource(mThumbIds[0]);
Toast.makeText(mContext, "Call", Toast.LENGTH_SHORT).show();
}
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if( convertView == null){
iView = new ImageView(mContext);
iView.setLayoutParams(new GridView.LayoutParams(85, 85));
iView.setScaleType(ImageView.ScaleType.CENTER_CROP);
iView.setPadding(8,8,8,8);
}else{
iView = (ImageView)convertView;
}
iView.setImageResource(mThumbIds[position]);
return iView;
}
private Integer[] mThumbIds = {
R.drawable.a_bhaibij, R.drawable.a_dashera, R.drawable.a_dipawali,
R.drawable.a_gandhi, R.drawable.a_holi, R.drawable.a_indepe,
R.drawable.a_janmastmi, R.drawable.a_kite, R.drawable.a_newyear
};
public void changeImage(){
iView.setImageResource(mThumbIds[5]);
}
}
Swaping the images in the GridView is very simple.What you have to do is
1* Store the cliked position,where you want to perform the swaping .
2* By using those two values perform the swap operation on mThumbIds array.
3* Finally invoke the notifyDataSetChanged() method on the Adapter object i.e im.notifyDataSetChanged();
public class MainActivity extends Activity {
/** Called when the activity is first created. */
int i=0;
int firstClick,secondClick;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView)findViewById(R.id.gridviewmy);
gridView.setAdapter(new ImageAdapter(this));
final ImageAdapter im = new ImageAdapter(this);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
i++;
if( i %2!=0){
firstClick=arg2;
}else{
secondClick=arg2;
Integer help=new Interger(mThumbIds[firstClick]);
mThumbIds[firstClick]=mThumbIds[secondClick];
mThumbIds[secondClick]=help;
notifyDataSetChanged();
System.out.println("Second Click "+i);
}
}
});
}
}
class ImageAdapter extends BaseAdapter{
private Context mContext;
ImageView iView;
public ImageAdapter(Context c){
this.mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
System.out.println("Item Is :-"+mThumbIds[position].toString());
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
System.out.println("Geting Id of Item "+mThumbIds[position]);
if(iView != null){
iView.setImageResource(mThumbIds[0]);
Toast.makeText(mContext, "Call", Toast.LENGTH_SHORT).show();
}
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if( convertView == null){
iView = new ImageView(mContext);
iView.setLayoutParams(new GridView.LayoutParams(85, 85));
iView.setScaleType(ImageView.ScaleType.CENTER_CROP);
iView.setPadding(8,8,8,8);
}else{
iView = (ImageView)convertView;
}
iView.setImageResource(mThumbIds[position]);
return iView;
}
private Integer[] mThumbIds = {
R.drawable.a_bhaibij, R.drawable.a_dashera, R.drawable.a_dipawali,
R.drawable.a_gandhi, R.drawable.a_holi, R.drawable.a_indepe,
R.drawable.a_janmastmi, R.drawable.a_kite, R.drawable.a_newyear
};
}
I think this may solve you problem.
All the best.
Also do the following for updating the grid view images to complete the swap operation:
im.notifyDataSetChanged();
gridView.setAdapter(im);
gridView.invalidateViews()
notifyDataSetChanged(); did not work for me. eclipse gave an error.
so instead of searching for the real solution, if there is one, I just reloaded the java page.
Of course I am saving the state of the images in the gridview (adapter) in internal storage in a file named graphics. So on reload of the java page it repaints with correct images.
It works.

Categories

Resources