[Android] 화면에 맞게 이미지 가져오기 ScalableNetworkImageView, volley

2020. 12. 28. 10:34모바일/Android_Java

step1) volly 의 NetworkImageView 를 상속하여 화면크기를 측정한다

public class ScalableNetworkImageView extends NetworkImageView {
    public boolean isMeasured = true;

    public ScalableNetworkImageView(Context context) {
        super(context);
    }

    public ScalableNetworkImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScalableNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            Drawable drawable = getDrawable();

            if (drawable == null) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            } else {
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = width * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
                setMeasuredDimension(width, height);
            }
        } catch (Exception e) {
            isMeasured = false;
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

}

step2) ImageLoader 객체를 생성한다

private ImageLoader mImageLoader;

FlickrVolley.init(this);
mImageLoader = FlickrVolley.getImageLoader();

step3) url로 이미지를 가져온다

ScalableNetworkImageView imgView = new ScalableNetworkImageView(this);
imgView.setImageUrl(imageUrl, mImageLoader);