Pour créer un pourcentage Pourcentage ImageView doit remplacer la méthode onMeasure dans ImageView.
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PercentageImageView extends ImageView {
public PercentageImageView(Context context) {
super(context);
}
public PercentageImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public PercentageImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public PercentageImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PercentageImageView, 0, 0);
try {
heightRatio = a.getFloat(R.styleable.PercentageImageView_imageHeightRatio, 0f);
} finally {
a.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
if (heightRatio != 0) {
height = (int) (heightRatio * width);
}
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
valeurs intérieur/attrs.xml
<resources>
<declare-styleable name="PercentageImageView">
<attr name="imageHeightRatio" format="float" />
</declare-styleable>
</resources>
Envoyer rapport du XML comme ci-dessous
<PercentageImageView
android:id="@+id/itemImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
app:imageHeightRatio="0.569" />// This is for 16:9 ratio.
Malheureusement, cela ne fonctionne pas avec la mise en page et des contraintes 0DP (contrainte de correspondance) au lieu de match_parent, une idée de ce qu'il faut faire dans la mise en page des contraintes? –