Gallery居左显示

做的项目查不清楚有多少了,但是很多有是同一个类型的。很多项目里都用到Gallery这个控件了,但是这个控件有一个影响视觉的地方,就是他默认的第一项是居中显示的,很多时候我们想让他居左显示,这种情况就需要我们自己写一个控制他位置的方法了,具体代码如下:

private void alignGalleryToLeft(View parentView, Gallery gallery) {
        int galleryWidth = parentView.getWidth();// 得到Parent控件的宽度
        // 在这边我们必须先从资源尺寸中得到子控件的宽度跟间距,因为:
        // 1. 在运行时,我们无法得到间距(因为Gallery这个类,没有这样的权限)
        // 2.有可能在运行得宽度的时候,item资源还没有准备好。

        int itemWidth = ProductActivity.this.getResources()
                .getDimensionPixelSize(R.dimen.gallery_item_width);
        int spacing = ProductActivity.this.getResources()
                .getDimensionPixelSize(R.dimen.gallery_spacing);
        // 那么这个偏移量是多少,我们将左边的gallery,以模拟的第一项的左对齐
        int offset;
        if (galleryWidth <= itemWidth) {
            offset = galleryWidth / 2 - itemWidth / 2 - spacing;
        } else {
            offset = galleryWidth - itemWidth - 2 * spacing;
        }
        // 现在就可以根据更新的布局参数设置做对齐了。
        MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
        mlp.setMargins(-itemWidth, mlp.topMargin, mlp.rightMargin,
                mlp.bottomMargin);
    }

上面的代码是在网上查找到的,略加修改,经测试没问题。

posted @ 2013-09-26 13:02  BetterMan-  阅读(361)  评论(0编辑  收藏  举报