在Android中居中水平Scrollview

时间:2015-08-12 19:32:54

标签: android

我有一个水平Scrollview的活动,其中只包含一个ImageView。当活动开始时,图像被加载到ImageView,我希望我的Horizo​​ntalScrollView在活动开始时出现在加载图像的中心。

我希望它出现在中心,但它一直出现在图片的最左边。 我用谷歌搜索并找到了一些建议,但在我的案例中都没有。我还在我的代码片段中包含了我已经尝试过的两种方法。

我错过了什么或做错了什么?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_preview);

    // setting image
    previewImage = (ImageView) findViewById(R.id.previewImage);
    Container item = Manager.picList.get(Manager.currentPreview);
    previewImage.setImageResource(item.imageId);

    // setting scrollview to center
    previewScroll = (HorizontalScrollView) findViewById(R.id.previewScroll);
    final int centerWidth = previewScroll.getChildAt(0).getWidth();

    // METHOD 1
    previewScroll.scrollTo(centerWidth/2,0);

    // METHOD 2
    previewScroll.post(new Runnable() {
        @Override
        public void run() {
            previewScroll.scrollTo(centerWidth/2,0);
        }
    });
}

1 个答案:

答案 0 :(得分:0)

这是你的解决方案:

private void scrollToCenter(final HorizontalScrollView horizontalScrollView)
{
    horizontalScrollView.getChildAt(0).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
    {
        @Override
        public void onGlobalLayout()
        {
            horizontalScrollView.scrollTo(horizontalScrollView.getChildAt(0).getWidth()/2,0);
        }
    });
}