Square ImageView
you can use :
app:layout_constraintDimensionRatio="1:1"
in this way:
<android.support.constraint.ConstraintLayout
android:id="@+id/lyt_img_cover"
android:layout_width="@dimen/image_top_episode"
android:layout_height="match_parent"
android:layout_centerInParent="false"
android:elevation="0dp"
android:foregroundGravity="center">
<ImageView
android:id="@+id/img_episode"
android:layout_width="0dp"
android:layout_height="0dp"
android:elevation="7dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</ImageView>
its layout should be ConstraintLayout
Create a separate class for defining the size dynamically for your ImageView that should inherit ImageView class as shown below:
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
int width = getMeasuredWidth();
setMeasuredDimension(width, width);
}
}
The setMeasuredDimension(width, width); will automatically set your height as the width.
In xml file use this class as a view in place of ImageView as shown below:
<com.packagepath.SquareImageView
android:id="@+id/Imageview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Set the Image view height at run time but first get the display width with this code
Display display = getWindowManager().getDefaultDisplay();
int swidth = display.getWidth();
and now set the height of image view like this
LayoutParams params = eventImage.getLayoutParams();
params.width = LayoutParams.FILL_PARENT;
params.height = swidth ;
eventImage.setLayoutParams(params);