I want to implement a drag-and-drop functionality within a recyclerview. Everything goes perfectly until I want to customize the looks of the view being dragged (not the view from which the drag event starts, I want to modify the "shadow" and keep the original view the same).
I've tried to make a bitmap out of the view being passed, but the end result is both the original item and the Shadow are modified AND the original view loses its position on the list... WTF
Here is my code:
public class ImageDragShadowBuilder extends View.DragShadowBuilder {
private Bitmap shadow;
LinearLayout linearLayout;
private ImageDragShadowBuilder() {
super();
}
public static ImageDragShadowBuilder create(Context context, View view) {
ImageDragShadowBuilder builder = new ImageDragShadowBuilder();
builder.linearLayout = (LinearLayout) view.findViewById(R.id.metric_item);
builder.linearLayout.setBackgroundResource(R.drawable.background_item_dragging);
builder.shadow = createBitmapFromView(builder.linearLayout);
return builder;
}
public View getLayout() {
return linearLayout;
}
private static Bitmap createBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
v.layout(0, 0, v.getWidth(), v.getHeight());
v.draw(new Canvas(b));
return b;
}
#Override
public void onDrawShadow(Canvas canvas) {
canvas.drawBitmap(shadow, 0, 0, null);
}
#Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
shadowSize.x = shadow.getWidth();
shadowSize.y = shadow.getHeight();
shadowTouchPoint.x = shadowSize.x / 2;
shadowTouchPoint.y = shadowSize.y / 2;
}
}
Any ideas?
I think that there are 2 problems :
Setting the background on the view attached to the RecyclerView affects the original item and the shadow
Triggering a layout changes the item's children position
Basically you can use the original view, but you should never modify it. A slightly modified version of your shadow builder could be :
public static ImageDragShadowBuilder create(Context context, View view) {
ImageDragShadowBuilder builder = new ImageDragShadowBuilder();
builder.linearLayout = (LinearLayout) view.findViewById(R.id.metric_item);
// do not change the original view
// we will draw the background directly later
// builder.linearLayout.setBackgroundResource(R.drawable.background_item_dragging);
builder.shadow = createBitmapFromView(builder.linearLayout);
return builder;
}
private static Bitmap createBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
// do not change the original view
// v.layout(0, 0, v.getWidth(), v.getHeight());
Canvas c = new Canvas(b);
// draw the background
Drawable background = v.getContext().getDrawable(R.drawable.background_item_dragging);
background.setBounds(0, 0, b.getWidth(), b.getHeight());
background.draw(c);
v.draw(c);
return b;
}
Related
I would like to show the custom marker to google map and cluster them. The marker contains a ImageView that will shows the avatar that is downloaded from network. Here is my target:
Everythings are OK, however, when I implemented the Google Maps Android Marker Clustering Utility, the ImageView shows the same avatar (sometime two wrong avatars).
Here is my custom MarkerRender:
public class MarkerRender extends DefaultClusterRenderer<Image> {
private static final String TAG = MarkerRender.class.getSimpleName();
private IconGenerator clusterGenerator;
private IconGenerator markerGenerator;
private ImageView mImgMarkerThumbnail;
private ImageView mImgMarkerClusterThumbnail;
private TextView txtSizeCluster;
private Activity activity;
private Bitmap mask, background;
private AtomicInteger imageDownloadCounter;
private int totalItem;
private ImageSize imageSize;
public MarkerRender(FragmentActivity activity, GoogleMap mMap, ClusterManager<Image> mClusterManager) {
super(activity, mMap, mClusterManager);
this.activity = activity;
imageDownloadCounter = new AtomicInteger(0);
mask = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.annotation_behind);
background = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.annotation_behind);
setUpClusterIcon();
setUpMarker();
}
private void setUpClusterIcon() {
clusterGenerator = new IconGenerator(activity);
View clusterView = activity.getLayoutInflater().inflate(R.layout.custom_marker_cluster, null);
txtSizeCluster = (TextView) clusterView.findViewById(R.id.tv_number_marker);
mImgMarkerClusterThumbnail = (ImageView) clusterView.findViewById(R.id.img_load);
clusterGenerator.setContentView(clusterView);
clusterGenerator.setBackground(null);
}
private void setUpMarker() {
markerGenerator = new IconGenerator(activity);
View markerView = activity.getLayoutInflater().inflate(R.layout.custom_marker, null);
mImgMarkerThumbnail = (ImageView) markerView.findViewById(R.id.img_load);
markerGenerator.setContentView(markerView);
markerGenerator.setBackground(null);
}
#Override
protected void onBeforeClusterItemRendered(final Image image, final MarkerOptions markerOptions) {
initImageSizeIfNeed();
Bitmap icon = markerGenerator.makeIcon();
PFLogManager.INSTANCE.logE(TAG, "maken icon: " + icon.hashCode());
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
icon.recycle();
}
#Override
protected void onClusterItemRendered(final Image image, Marker marker) {
super.onClusterItemRendered(image, marker);
ImageLoader.getInstance().loadImage(image.getMapImageLink(), imageSize,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
Bitmap croppedBitmap = Helpers.makeCroppedBitmap(loadedImage, background, mask);
mImgMarkerThumbnail.setImageBitmap(croppedBitmap);
}
});
}
#Override
protected void onBeforeClusterRendered(Cluster<Image> cluster, MarkerOptions markerOptions) {
initImageSizeIfNeed();
Bitmap icon = clusterGenerator.makeIcon();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));
icon.recycle();
}
#Override
protected void onClusterRendered(Cluster<Image> cluster, Marker marker) {
super.onClusterRendered(cluster, marker);
ArrayList<Image> list = new ArrayList<>(cluster.getItems());
setTextNumberMarker(cluster);
String urlFirstImage = list.get(0).getMapImageLink();
ImageLoader.getInstance().loadImage(urlFirstImage, imageSize,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
final Bitmap croppedBitmap = Helpers.makeCroppedBitmap(loadedImage, background, mask);
mImgMarkerClusterThumbnail.setImageBitmap(croppedBitmap);
}
});
}
private void loadClusterThumbnail(String url) {
}
private void setTextNumberMarker(Cluster<Image> cluster) {
int size = cluster.getSize();
if (size > 99) {
txtSizeCluster.setText("99+");
} else {
txtSizeCluster.setText(String.valueOf(cluster.getSize()));
}
}
#Override
protected boolean shouldRenderAsCluster(Cluster cluster) {
return cluster.getSize() > 1;
}
}
I've guess that the issue is I use only one ImageView to show those avatar, so I try to use unique ImageView for each marker (by inflat new one from xml every time needed), but the result is they are all show the blank marker (just the background and there is no avatar).
I've resolved it myself. My solution is use the Marker.setIcon() method after the image is downloaded from netword or got from cache. I dont use the ImageView anymore.
So, i modified the above MarkerRender class:
The setUpClusterIcon() method:
private void setUpClusterIcon() {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(markerWidth, markerHeight);
ImageView marker = new ImageView(activity);
marker.setLayoutParams(params);
clusterGenerator = new IconGenerator(activity);
clusterGenerator.setContentView(marker);
clusterGenerator.setBackground(null);
}
And the onClusterItemRendered() method:
protected void onClusterItemRendered(final Image image, final Marker marker) {
super.onClusterItemRendered(image, marker);
ImageLoader.getInstance().loadImage(image.getMapImageLink(), imageSize,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
Bitmap croppedBitmap = Helpers.makeClusterItemBitmap(background, loadedImage, mask);
try {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(croppedBitmap));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Also the makeClusterItemBitmap helper method:
public static Bitmap makeClusterItemBitmap(Bitmap background, Bitmap original, Bitmap mask) {
Bitmap croppedOriginal = makeCroppedBitmap(original, mask);
Bitmap result = Bitmap.createBitmap(background.getWidth(), background.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
croppedOriginal = Bitmap.createScaledBitmap(croppedOriginal, croppedOriginal.getWidth() - 20, croppedOriginal.getHeight() - 20, true);
mCanvas.drawBitmap(background, 0, 0, null);
mCanvas.drawBitmap(croppedOriginal, 10, 10, null);
return result;
}
public static Bitmap makeCroppedBitmap(Bitmap original, Bitmap mask) {
original = Bitmap.createScaledBitmap(original, mask.getWidth(),
mask.getHeight(), true);
Bitmap result = Bitmap.createBitmap(original.getWidth(), original.getHeight(),
Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
mCanvas.drawBitmap(original, 0, 0, null);
mCanvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
return result;
}
Done, finish three nightmare researchingdays days :P
However, this approach leads new issue: the performance. Cause by drawing new bitmap with many layers, the map is laggy a bit. I'm thinking in improving this :)
Any sugguestion are appriciate :D
When I'm trying to scale my canvas to a draw SCALED view, my view is actually scaled, but view is getting clipped. (probably because of its layout parameters?)
public void onDraw(Canvas canvas) {
canvas.scale(2f, 2f);
view.draw(canvas);
}
simple image:
image after new onDraw called, for example when I click this button:
The button should be full sized when canvas is scaled. Do you have any ideas how to solve it?
p.s. call of
view.invalidate();
view.requestLayout();
doesn't help.
I'm using MyDragShadowBuilder because I want my view to be double sized when I drag the view.
private final class MyDragShadowBuilder extends DragShadowBuilder {
public MyDragShadowBuilder(View view) {
super(view);
}
#Override
public void onDrawShadow(Canvas canvas) {
final View view = getView();
if (view != null) {
canvas.scale(2f, 2f);
view.draw(canvas);
} else {
Log.e("DragShadowBuilder", "Asked to draw drag shadow but no view");
}
}
I add my view into my Absolute Layout implementation with WRAP_CONTENT layout properties
I ran into the same trouble. After some time i found a way to make it work :)
This scales the original view by a factor of 4.
private static class MyDragShadowBuilder extends View.DragShadowBuilder {
private static final int SCALING_FACTOR = 4;
public MyDragShadowBuilder(View view) {
super(view);
}
#Override
public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
View v = getView();
final int width = v.getWidth() * SCALING_FACTOR;
final int height = v.getHeight() * SCALING_FACTOR;
shadowSize.set(width, height);
shadowTouchPoint.set(width / 2, height / 2);
}
#Override
public void onDrawShadow(Canvas canvas) {
canvas.scale(SCALING_FACTOR, SCALING_FACTOR);
getView().draw(canvas);
}
}
I am a programmer with a Windows background and I am new to Java and Android stuff.
I want to create a widget (not an app) which displays a chart. After a long research I know I can do this with Canvas, imageviews and Bitmaps. The canvas which I paint on should be the same as the Widget Size.
How do I know the widget size (or imageview size) so that I can supply it to the function?
Bitmap.createBitmap(width_xx, height_yy, Config.ARGB_8888);
Code Snippet:
In the timer run method:
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(??, ??, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Create a new paint
Paint p = new Paint();
p.setAntiAlias(true);
p.setStrokeWidth(1);
// Draw circle
// Here I can use the width and height to scale the circle
canvas.drawCircle(50, 50, 7, p);
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);
From what I've learnt, you can only calculate widget dimensions on Android 4.1+.
When on a lower API, you'll have to use static dimensions.
About widget dimensions: App Widget Design Guidelines
int w = DEFAULT_WIDTH, h = DEFAULT_HEIGHT;
if ( Build.VERSION.SDK_INT >= 16 ) {
Bundle options = appWidgetManager.getAppWidgetOptions(widgetId);
int maxW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
int maxH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
int minW = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH);
int minH = options.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT);
if ( context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ) {
w = maxW;
h = minH;
} else {
w = minW;
h = maxH;
}
}
Have a look at the method:
public void onAppWidgetOptionsChanged (Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions)
It will be called each time you start/resize the widget.
Getting the widget width/height can be done as follows:
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT)
newOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT)
I am currently using this:
private void run() {
int width = 400, height = 400;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Paint p = new Paint();
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(1);
p.setAntiAlias(true);
c.drawCircle(width/2, height/2, radius, p);
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);
ComponentName clockWidget = new ComponentName(context,
Clock_22_analog.class);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
appWidgetManager.updateAppWidget(clockWidget, remoteViews);
}
You can use this
Bitmap image1, image2;
Bitmap bitmap = Bitmap.createBitmap(image1.getWidth(), image1.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
You can create a custom widget and set the size of wight on its onMeasure() method. And also save the size at that time so that you can use it further for image creation...
I've not worked on Widgets, but I have some experience getting ImageView's size.
Here is some code I use:
public class ViewSizes {
public int width;
public int height;
public boolean isEmpty() {
boolean result = false;
if (0 >= width || 0 >= height) {
result = true;
}
return result;
}
}
That's just a dummy class containing the size parameters.
public static ViewSizes getSizes(View view) {
ViewSizes sizes = new ViewSizes();
sizes.width = view.getWidth();
sizes.height = view.getHeight();
if (sizes.isEmpty()) {
LayoutParams params = view.getLayoutParams();
if (null != params) {
int widthSpec = View.MeasureSpec.makeMeasureSpec(params.width, View.MeasureSpec.AT_MOST);
int heightSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.AT_MOST);
view.measure(widthSpec, heightSpec);
}
sizes.width = view.getMeasuredWidth();
sizes.height = view.getMeasuredHeight();
}
return sizes;
}
This method calculates the width forcing a measure cycle if such has not already happened.
public static boolean loadPhoto(ImageView view, String url, float aspectRatio) {
boolean processed = false;
ViewSizes sizes = ViewsUtils.getSizes(view);
if (!sizes.isEmpty()) {
int width = sizes.width - 2;
int height = sizes.height - 2;
if (ASPECT_RATIO_UNDEFINED != aspectRatio) {
if (height * aspectRatio > width) {
height = (int) (width / aspectRatio);
} else if (height * aspectRatio < width) {
width = (int) (height * aspectRatio);
}
}
// Do you bitmap processing here
processed = true;
}
return processed;
}
This one is probably useless for you. I give just as an example - I have an ImageView and image URL, which should be parametrized with image and height.
public class PhotoLayoutListener implements OnGlobalLayoutListener {
private ImageView view;
private String url;
private float aspectRatio;
public PhotoLayoutListener(ImageView view, String url, float aspectRatio) {
this.view = view;
this.url = url;
this.aspectRatio = aspectRatio;
}
boolean handled = false;
#Override
public void onGlobalLayout() {
if (!handled) {
PhotoUtils.loadPhoto(view, url, aspectRatio);
handled = true;
}
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
removeLayoutListenerPre16(viewTreeObserver, this);
} else {
removeLayoutListenerPost16(viewTreeObserver, this);
}
}
}
#SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeGlobalOnLayoutListener(listener);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void removeLayoutListenerPost16(ViewTreeObserver observer, OnGlobalLayoutListener listener){
observer.removeOnGlobalLayoutListener(listener);
}
}
This is just a layout listener - I want to process the image loading once the layout phase has finished.
public static void setImage(ImageView view, String url, boolean forceLayoutLoading, float aspectRatio) {
if (null != view && null != url) {
final ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (forceLayoutLoading || !PhotoUtils.loadPhoto(view, url, aspectRatio)) {
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new PhotoLayoutListener(view, url, aspectRatio));
}
}
}
}
This is the method I actually call. I give it the view and URL. The methods takes care of loading - if it can determine the view's size it starts loading immediately. Otherwise it just assigns a layout listener and start the loading process once the layout is finished.
You could strip away some parameters - forceLoading / aspectRatio should be irrelevant for you. After that change the PhotoUtils.loadPhoto method in order to create the bitmap with the width / height it has calculated.
Like Julian told us, you can get them like that with a bitmap of your image:
int width = bitmap.getWidth();
int height = bitmap.getHeight();
I do not get a grip on solving the issue.
I have manually placed two images on the screen. I would like to have an onClick event handling for each of it.
By the following approach, the OnClick Handler seems to be valid only for the background.
Acually, all created sub-views/Imagers and their onClickListeners are reacting on the parent where they have drawn onto.
The AndroidManifext.xml is only the RelativeLayout with no child tags.
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Imager theUpperImage = new Imager( R.drawable.img1, -25, -100, new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText( v.getContext(), "Upper", Toast.LENGTH_SHORT).show();
}
});
addContentView( theUpperImage, new View.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
final Imager theLowerImage = new Imager( R.drawable.img2, -25, +50, new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText( v.getContext(), "Lower", Toast.LENGTH_SHORT).show();
}
});
addContentView( theLowerImage, new View.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
class Imager extends View {
final int resImage;
final int centerOffsetX, centerOffsetY;
public Imager(int inResImage, int inCenterOffsetX, int inCenterOffsetY, View.OnClickListener inOnClickListener) {
super( Main.this );
resImage = inResImage;
centerOffsetX = inCenterOffsetX;
centerOffsetY = inCenterOffsetY;
super.setOnClickListener( inOnClickListener );
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resImage);
final int x = (canvas.getWidth()/2)+centerOffsetX;
final int y = (canvas.getWidth()/2)+centerOffsetY;
canvas.drawBitmap(bitmap, x, y, null);
}
#Override
public void draw(Canvas canvas) {
super.draw( canvas );
final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resImage);
final int x = (canvas.getWidth()/2)+centerOffsetX;
final int y = (canvas.getWidth()/2)+centerOffsetY;
canvas.drawBitmap(bitmap, x, y, null);
}
}
}
How to created freely placed images and provide them with an OnClick-functionality?
I would not stick to the above solution. Important for me is to freely place the images on the screen and have them clickable. The predefined Layouts semm not to give me a certain Layout which have a FreeLayout-functionality. (Or is the intention of Layout misleading me?)
I also keep in mind that I probably want to dynamicly remove an Image later, but I am not there yet.
Thank you a lot for help in advance,
Dirk
I have set up a gallery for my app using BaseAdapter. Here is the code I used for the gallery.
homeGallery = (Gallery) findViewById(R.id.homeimggallery);
homeGallery.setSpacing(0);
homeGallery.setSelection(0);
homeGallery.setAdapter(new AddImgAdp(this));
private class AddImgAdp extends BaseAdapter {
private int GalItemBg, temp;
private Context cont;
private View convertView1;
private ViewGroup parent1;
private Bitmap mask = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.mask);
private Bitmap whiteBorder = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.stroke);
private Bitmap blueBorder = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.strokeactive);
private Bitmap src;
private Bitmap dest;
private Canvas canvas;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private ImageView homeImgView;
private ImageView[] homeImgViewArr= new ImageView[arrThumbImage.length];
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
}
public int getCount() {
return arrThumbImage.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
homeImgView = new ImageView(cont);
try{
src = BitmapFactory.decodeResource(mContext.getResources(), arrThumbImage[position]);
dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
canvas = new Canvas(dest);
canvas.drawColor(Color.TRANSPARENT);
canvas.save();
canvas.translate((canvas.getWidth() - src.getWidth())>> 1, (canvas.getHeight() - src.getHeight())>> 1);
canvas.drawBitmap(src, 0, 0, null);
canvas.drawBitmap(mask, 0, 0, paint);
canvas.drawBitmap(dest, 0, 0, paint);
homeImgView.setBackgroundDrawable(new BitmapDrawable(dest));
homeImgView.setImageResource(R.drawable.stroke);
homeImgView.setScaleType(ImageView.ScaleType.FIT_XY);
homeImgViewArr[position] = homeImgView;
} catch(Exception e) {}
return homeImgView;
}
}
The gallery looks like below:
On finger movement, it is moving right to left or left to right as expected. Now I want to add some onClick action to items. If user click on any image, it will be selected and align in the middle. The following code is used for this action.
homeGallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
homeGallery.setSelection(position);
}
});
But it results wrongly. If I am selecting item no. 2, the item no. 3 got selected, although setSelection action is firing against item no 2. If I click on the right most item of the above pic, it is resulting line below:
What is the problem in my code?
I'm working with a Gallery myself, but I'm not quite sure what the problem is here, since your code is further than where I stand.
Anyways, since you click item 3?? and you get item 4 centered I can think of a few options:
-Something is wrong with the array indexes, might wanna take a log of the positions.
-Personally, I work with an array of Integer and on the getView() I just get the position which is easier than what you're doing I believe.
public ArrayList mImageIds = new ArrayList(); the array...
i.setImageResource(mImageIds.get(position)); and in getView() it's sorted.
Hope this is helpful