Android如何在Horizo​​ntalScrollView中关注下一个Image

时间:2015-03-18 17:40:55

标签: android gallery horizontal-scrolling horizontalscrollview

我正在尝试创建Horizo​​ntalScrollView来显示一些图像(不推荐使用图库,我不想使用ViewPager)。画廊看起来像这样: enter image description here

问题是,我不知道如何将一个图像聚焦在Horizo​​ntalScrollView的中心,就像在图库中一样。如果我向右滚动,下一个图像将出现在屏幕的中央。 他们是使用Horizo​​ntalScrollView的方法吗?

1 个答案:

答案 0 :(得分:0)

使用此自定义Horizo​​ntalScrollView。在此,您需要将位置传递给setCenter以使其居中。

摘自here

public class CenterLockHorizontalScrollview extends HorizontalScrollView {

        Context context;

        int prevIndex = 0;

     

        public CenterLockHorizontalScrollview(Context context, AttributeSet attrs) {

            super(context, attrs);

            this.context = context;

            this.setSmoothScrollingEnabled(true);

     

        }

     

        public void setAdapter(Context context, CustomListAdapter mAdapter) {

     

            try {

                fillViewWithAdapter(mAdapter);

            } catch (ZeroChildException e) {

     

                e.printStackTrace();

            }

        }

     

        private void fillViewWithAdapter(CustomListAdapter mAdapter)

                throws ZeroChildException {

            if (getChildCount() == 0) {

                throw new ZeroChildException(

                        "CenterLockHorizontalScrollView must have one child");

            }

            if (getChildCount() == 0 || mAdapter == null)

                return;

     

            ViewGroup parent = (ViewGroup) getChildAt(0);

     

            parent.removeAllViews();

     

            for (int i = 0; i < mAdapter.getCount(); i++) {

                parent.addView(mAdapter.getView(i, null, parent));

            }

        }

     

        public void setCenter(int index) {

     

            ViewGroup parent = (ViewGroup) getChildAt(0);

     

            View preView = parent.getChildAt(prevIndex);

            preView.setBackgroundColor(Color.parseColor("#64CBD8"));

            android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(

                    LinearLayout.LayoutParams.WRAP_CONTENT,

                    LinearLayout.LayoutParams.WRAP_CONTENT);

            lp.setMargins(5, 5, 5, 5);

            preView.setLayoutParams(lp);

     

            View view = parent.getChildAt(index);

            view.setBackgroundColor(Color.RED);

     

            int screenWidth = ((Activity) context).getWindowManager()

                    .getDefaultDisplay().getWidth();

     

            int scrollX = (view.getLeft() - (screenWidth / 2))

                    + (view.getWidth() / 2);

            this.smoothScrollTo(scrollX, 0);

            prevIndex = index;

        }

     

    }