1、獲取屏幕寬度
ViewTreeObserver vto = journalismTitleEditor.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
journalismTitleEditor.getViewTreeObserver().removeGlobalOnLayoutListener(this);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; // 屏幕寬度(像素)
// int height = dm.heightPixels; // 屏幕高度(像素)
screenWidth = width; // 獲取屏幕寬度
LogUtils.i("屏幕寬度=" + screenWidth);
}
});
2、更改控件寬高
SimpleTarget<Bitmap> target = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
if (resource != null) {
int imageWidth = resource.getWidth();
int imageHeight = resource.getHeight();
LogUtils.i("圖片寬=" + imageWidth + " 圖片高=" + imageHeight);
int width = imageWidth;
int height = imageHeight;
if (imageWidth > screenWidth) {
width = screenWidth;//固定寬度
//寬度固定,然後根據原始寬高比得到此固定寬度需要的高度
height = width * imageHeight / imageWidth;
}
ViewGroup.LayoutParams para = imageView.getLayoutParams();
para.height = height;
para.width = width;
imageView.setImageBitmap(resource);
imageView.setLayoutParams(para);
}
}
};
String url = item.getImagePath();
if (!TextUtils.isEmpty(url)) {
url = url.trim();
if (url.startsWith("http")) {
url = url.replace("http", "https");
}
}
Glide.with(mContext).asBitmap().load(url).into(target);
<LinearLayout
android:id="@+id/layout_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/border_news_image"
android:gravity="center"
android:minHeight="90dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:id="@+id/item_content_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:visibility="visible"
tools:src="@mipmap/writing_icon_bg" />
</LinearLayout>
最終效果