将一个 ImageView 放在中心,宽度和高度是父宽度的一半?

Ahm*_*med 5 android android-imageview

我想将一个 ImageView 放在一个 ViewGroup(最好是一个 RelativeLayout)中,如下所示。视图组被拉伸以占据活动的整个宽度和高度。我想确保无论设备宽度是 ImageView 的高度和宽度都应该是它的一半..

?????????????????????????   
?                       ? 
?       View Group      ? 
?                       ? 
?    ???????????????    ?   
?    ?             ?    ?   
?    ? ImageView   ?    ?   
?    ?             ?    ?   
?    ? width = X/2 ?    ?   
?    ? height= X/2 ?    ?   
?    ???????????????    ?   
?                       ? 
?                       ? 
?                       ? 
?????????????????????????   
<----------------------->
Xpx width of Device/Viewgroup
Run Code Online (Sandbox Code Playgroud)

有人可以请帮助我如何实现这一目标?

Luc*_*ord 0

也许尝试这样的事情:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

可能不需要对父级进行空检查,但应该相应地调整图像大小