I am trying to make a listview with direction pointers in the list items just like gooing latitude:
http://www.eurodroid.com/pics/android_google_maps_latitude_update_2.png
I already have working code, but i am worried about the performance.
Everytime the orientation sensor(thats a lot) the code rebuilds the entire list with the listview adapter when i only want to rotate the direction pointer image, so it is doing to same as calling for notifyDataSetChanged.
I tried to see what happens if i only call for an setText() whenever the sensor changes, i found out that it does not rebuild the entire list then.
public class SensorWatcher{
private SensorManager mgr = null;
public float azimuth = 0;
private Main main;
SensorWatcher(Main mainContext){
main = mainContext;
mgr = (SensorManager)mainContext.getSystemService(Context.SENSOR_SERVICE);
mgr.registerListener(listener, mgr.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
}
private SensorEventListener listener = new SensorEventListener() {
int newAzimuth;
public void onSensorChanged(SensorEvent e) {
if (e.sensor.getType()==Sensor.TYPE_ORIENTATION) {
newAzimuth = Math.round(e.values[0]);
if(newAzimuth != azimuth){
azimuth= newAzimuth;
updateItems();
//main.adapter.notifyDataSetChanged();
}
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
public void updateItems(){
ListView list = main.list;
ImageView img;
View listItem;
if(list != null){
for(int i =list.getFirstVisiblePosition();i<=list.getLastVisiblePosition();i++ ){
if(i< list.getChildCount()){
listItem=(View) list.getChildAt(i);
//listItem = list.getAdapter().getView(i, null, null);
img =(ImageView) listItem.findViewById(R.id.allowtest);
Bitmap bmp = BitmapFactory.decodeResource(main.getResources(), R.drawable.arrowup);
Matrix mtx = new Matrix();
mtx.postRotate(calculateDirection(list,i));
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mtx, true);
BitmapDrawable bmd = new BitmapDrawable(rotatedBMP);
img.setImageDrawable(bmd);
}
}
}
}
For making changes in the list u need to call notifyDataSetChanged.. There is no other alternative for that .
Related
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;
}
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
I am using a GridView to display images. The images are downloaded from a feed and added to a BitmapCache. The GridView is inside of a ViewFlipper (which has a ListView as second View). I'm using GridView for the first time but I've worked with Adapters many times when I used ListViews.
At the moment, the feed only delivers two images. But when I start my Fragment containing the GridView I get an OutOfMemoryError caused bei BitmapFactory.decodeStream(). When I took a deeper look into the logcat, I noticed that getView() inside of my Adapter for the GridView is called many many times.
I know that it's nothing special if getView() is called more than once, but the getView()-method in my Adapter gets called over 120 times only for position 0. And I don't really understand why it's called so often. But I'm pretty sure that this caused my memory problem as this method tries to load a bitmap over 100 times in just a few seconds.
As I'm already trying to recycle my view with a ViewHolder I'm quite helpless at the moment and I hope somebody can explain me this massive calls of getView() and/or might give me a hint to solve my problem.
The getView()-mthod of my adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.pictures_grid_item, parent, false);
holder.image = (ImageView) convertView.findViewById(R.id.picturesGridImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.image.setImageBitmap(null);
}
Picture picture = (Picture) pictureList.get(position);
String imageUrl = picture.getUrl();
if (!TextUtils.isEmpty(imageUrl)) {
holder.image.setTag(imageUrl);
ImageLoader.getInstance(context).loadImageWithTagCheck(holder.image);
}
return convertView;
}
private static class ViewHolder {
ImageView image;
}
The loadImageWithTagCheck()-method just checks if the image has already been downloaded (which deffinitely should be the case)
The Fragment which holds the View:
public class PicturesFragment extends BaseFragment {
private List<Parcelable> pictureList;
private PicturesGridAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.pictures_fragment, container, false);
// TODO: Remove final after development
final MediaActivity activity = (MediaActivity) getActivity();
pictureList = activity.getPictures();
adapter = new PicturesGridAdapter(activity, pictureList);
GridView gridview = (GridView) view.findViewById(R.id.picturesGrid);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(activity, "" + position, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
BTW: I'm not using *wrap_content* anywhere.
Edit:
Here's the code of the imageloader. Ofcourse, the ImageLoader is the problem which causes the outOfMemoryError. But I think that the problem is rather something with the adapter because 120 calls of getView() for position 0 just after creating the view can't be right. And the Adapter is just created once so it's >120 calls in a single instance of my adapter.
(this is a pretty huge and complex project so the "simple" imageloader has a lot of code)
public void loadImageWithTagCheck(final ImageView view) {
final String url = (String) view.getTag();
final Handler uiHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
}
};
if (imageHandler != null) {
imageHandler.post(new Runnable() {
#Override
public void run() {
final Bitmap bmp = getImage(url, view);
uiHandler.post(new Runnable() {
#Override
public void run() {
String tagUrl = (String) view.getTag();
if (tagUrl.equals(url) && bmp != null
&& !bmp.isRecycled()) {
scaleBitmapAndAdjustViewByHeight(view, bmp);
} else if (bmp != null) {
bmp.recycle();
}
}
});
}
});
}
}
private Bitmap getImage(String url, View v) {
Bitmap bmp = null;
if (url != null && !TextUtils.isEmpty(url)) {
String md5Url = Utility.md5(url);
if (cache.containsKey(md5Url)) {
bmp = cache.getBitmap(md5Url);
} else {
HttpGet httpGet = new HttpGet();
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
try {
URI uri = new URI(url);
httpGet.setURI(uri);
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
final BufferedInputStream buffIn = new BufferedInputStream(
entity.getContent(), Utils.IO_BUFFER_SIZE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.outWidth = v.getWidth();
options.outHeight = v.getHeight();
options.inPurgeable = true;
options.inInputShareable = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
bmp = BitmapFactory.decodeStream(buffIn, null,
options);
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
if (bmp != null) {
cache.put(md5Url, bmp);
}
}
}
return bmp;
}
private void scaleBitmapAndAdjustViewByHeight(final ImageView view,
final Bitmap bmp) {
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(
this);
} else {
view.getViewTreeObserver().removeGlobalOnLayoutListener(
this);
}
// Get current dimensions
int width = bmp.getWidth();
int height = bmp.getHeight();
// Determine how much to scale: the dimension requiring less
// scaling is closer to the its side. This way the image always
// stays inside your bounding box AND either x/y axis touches
// it.
int imageViewHeightFromXMLinPixels = view.getHeight();
float xScale = (float) ((imageViewHeightFromXMLinPixels * 2.75) / width);
float yScale = ((float) imageViewHeightFromXMLinPixels)
/ height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap
Bitmap scaledBitmap = Bitmap.createBitmap(bmp, 0, 0, width,
height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
view.setImageBitmap(scaledBitmap);
view.getLayoutParams().width = width;
}
});
view.requestLayout();
}
Get rid of the scaleBitmapAndAdjustViewByHeight(...) method.
Instead, do a simple view.setImageBitmap(bmp).
Why?
scaleBitmapAndAdjustViewByHeight(...) calls view.requestLayout() which probably leads to calling your adapters getView(...) and ends in a deadlock and finally the OutOfMemoryError.
Can anyone help me to do this.
I am trying to build an android app but stuck in between.
i have use the following code to move a image.
iv is ImageView object
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
code:
public class gameLogic extends Activity
{
ImageView image;
TranslateAnimation moveImage;
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.game_logic);
imageMoveRandom(imageList(image,0));
}
ImageView imageList(ImageView v,int i)
{
v = (ImageView) findViewById(R.id.rabbit);
int imgId;
int j = i;
TypedArray imgs = getResources().obtainTypedArray(R.array.random_imgs);
//get resourceid by index
imgId = imgs.getResourceId(j, 0);
// or set you ImageView's resource to the id
v.setBackgroundResource(imgId);
return v;
}
void imageMoveRandom(ImageView iv)throws NotFoundException
{
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int xDest = dm.widthPixels/2;
int yDest = dm.heightPixels/2;
// Toast.makeText(gameLogic.this, dm.widthPixels, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, dm.heightPixels, 2000).show();
moveImage = new TranslateAnimation( 0, xDest, 0, -yDest);
moveImage.setDuration(1000);
moveImage.setFillAfter( true );
iv.startAnimation(moveImage);
//moveImage.reset();
}
}
Above is not full code..but part which may be helpful for references.
But i want to continuously move the image in random place but within the android display.
Can any one suggest the solution.
Thanks in Advance :)
class BitmapView extends View
{
changingX=10;
changingY=10;
public BitmapView(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.yourImageName);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, changingX,changingY, null);
changingX=changingX+5;
changingY=changingY+10;
invalidate();
}
}
Try this
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