Maybe try something like this:
public class CenteredImageView extends ImageView {
public CenteredImageView(Context context) {
super(context);
}
public CenteredImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CenteredImageView(Context context, AttributeSet attrs, int id) {
super(context, attrs, id);
}
@Override
public void onMeasure(int measuredWidth, int measuredHeight) {
super.onMeasure(measuredWidth, measuredHeight);
ViewGroup parent = (ViewGroup) getParent();
if(parent != null){
int width = parent.getMeasuredWidth() / 2;
setMeasuredDimension(width, width);
}
}
It may not be necessary to perform a null check on the parent element, but the image size should be appropriately
source
share