您现在的位置:首页 > 博客 > Android开发 > UI开发 > 正文
Android how to make Gallery auto scroll to first item
http://www.drovik.com/      2013-10-18 22:46:28      来源:www.drovik.com      点击:

private void alignGalleryToLeft(Gallery gallery) {

WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int galleryWidth = manager.getDefaultDisplay().getWidth(); // We are taking the item widths and spacing from a dimension resource // because: // 1. No way to get spacing at runtime (no accessor in the Gallery // class) // 2. There might not yet be any item view created when we are calling // this // function int itemWidth = getsize(105); int spacing = getsize(10); // The offset is how much we will pull the gallery to the left in order // to simulate left alignment of the first item final int offset; if (galleryWidth <= itemWidth) { offset = galleryWidth / 2 - itemWidth / 2 - spacing; } else { offset = galleryWidth - itemWidth - 2 * spacing; } // Now update the layout parameters of the gallery in order to set the // left margin MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams(); mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin, mlp.bottomMargin); }

getsize() is a method:

public int getsize(int sizeInDip) { DisplayMetrics metrics = new DisplayMetrics(); metrics = getResources().getDisplayMetrics(); return (int) ((sizeInDip * metrics.density) + 0.5); }

pass your value in DPI into this method.

Hope,it will work for you.

分享到:
发表评论(0)
姓名 *
评论内容 *
验证码 *图片看不清?点击重新得到验证码