How do I resize my imageview within my scrollview as it is done in this image?

后端 未结 1 745
名媛妹妹
名媛妹妹 2021-01-31 09:37

I have created a scrollview and an imageview is placed within it. I\'d like on scroll for it to resize in the same fashion it is done in the image below but so far I\'ve had lit

1条回答
  •  清歌不尽
    2021-01-31 09:44

    There is simple example below that shows how to achieve parallax effect.

    First, put your ImageView and other views into FrameLayout:

    
    
        
    
            
    
            
    
                
    
            
    
        
    
    

    LinearLayout's top margin is equal to the ImageViews's height (@dimen/contact_photo_height in our example).

    Then we should listen scroll position of the ScrollView and change the position of ImageView:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        <...>
    
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        mPhotoIV = (ImageView) findViewById(R.id.contactPic);
        mWrapperFL = (FrameLayout) findViewById(R.id.flWrapper);
    
        mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ScrollPositionObserver());
    
        <...>
    }
    
    private class ScrollPositionObserver implements ViewTreeObserver.OnScrollChangedListener {
    
        private int mImageViewHeight;
    
        public ScrollPositionObserver() {
            mImageViewHeight = getResources().getDimensionPixelSize(R.dimen.contact_photo_height);
        }
    
        @Override
        public void onScrollChanged() {
            int scrollY = Math.min(Math.max(mScrollView.getScrollY(), 0), mImageViewHeight);
    
            // changing position of ImageView
            mPhotoIV.setTranslationY(scrollY / 2);
    
            // alpha you could set to ActionBar background
            float alpha = scrollY / (float) mImageViewHeight;
        }
    }
    

    0 讨论(0)
提交回复
热议问题