|
public class PercentImageView extends AppCompatImageView { |
|
|
|
private int WIDTH_PERCENT = Integer.MIN_VALUE; |
|
private int HEIGHT_PERCENT = Integer.MIN_VALUE; |
|
|
|
public PercentImageView(Context context) { |
|
super(context); |
|
init(context, null); |
|
} |
|
|
|
public PercentImageView(Context context, AttributeSet attrs) { |
|
super(context, attrs); |
|
init(context, attrs); |
|
} |
|
|
|
public PercentImageView(Context context, AttributeSet attrs, int defStyleAttr) { |
|
super(context, attrs, defStyleAttr); |
|
init(context, attrs); |
|
} |
|
|
|
private void init(Context context, AttributeSet attrs) { |
|
if (attrs == null) return; |
|
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, |
|
R.styleable.PercentImageView, 0, 0); |
|
try { |
|
WIDTH_PERCENT = a.getInteger(R.styleable.PercentImageView_piv_widthPercent, Integer.MIN_VALUE); |
|
HEIGHT_PERCENT = a.getInteger(R.styleable.PercentImageView_piv_heightPercent, Integer.MIN_VALUE); |
|
} finally { |
|
a.recycle(); |
|
} |
|
} |
|
|
|
@Override |
|
protected void onAttachedToWindow() { |
|
super.onAttachedToWindow(); |
|
ViewGroup.LayoutParams viewParams = getLayoutParams(); |
|
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); |
|
int height = (int) (metrics.heightPixels * (HEIGHT_PERCENT / 100f)); |
|
int width = (int) (metrics.widthPixels * (WIDTH_PERCENT / 100f)); |
|
if (HEIGHT_PERCENT != Integer.MIN_VALUE) |
|
viewParams.height = height; |
|
if (WIDTH_PERCENT != Integer.MIN_VALUE) |
|
viewParams.width = width; |
|
setLayoutParams(viewParams); |
|
} |
|
} |