Skip to content

Instantly share code, notes, and snippets.

@lesterlopez-dev
Last active August 28, 2018 02:43
Show Gist options
  • Save lesterlopez-dev/faf24b17196a3a8c38b24a9b75672da8 to your computer and use it in GitHub Desktop.
Save lesterlopez-dev/faf24b17196a3a8c38b24a9b75672da8 to your computer and use it in GitHub Desktop.
PercentImageView is an extension for ImageView that can control W & H by percentage.

PercentImageView

To implement it into xml

<PercentImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:piv_heightPercent="50"
    app:piv_widthPercent="50"/>
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);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="PercentImageView">
<attr name="piv_heightPercent" format="integer" />
<attr name="piv_widthPercent" format="integer" />
</declare-styleable>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment