android ImageView 寬度設定,高度自適應

最近碰到一個需求,要求是在不知道圖片寬度和高度的狀況下,讓圖片在指定寬度內充滿,同時高度自適應,在網絡上查找了一下,也有不少解決方法,後來針對本身的應用,選擇了一個修改較小的方案,最後證實效果仍是蠻不錯的,記錄在這裏,但願能幫助到有一樣需求的人。android

首先,須要給你的ImageView佈局加上android:adjustViewBounds="true"網絡

 <ImageView
            android:id="@+id/iv_custom_showdress_item_dress"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"/>

而後,在代碼裏設置ImageView.最大寬度和最大高度,由於adjustViewBounds屬性只有在設置了最大高度和最大寬度後纔會起做用佈局

WindowManager wm = (WindowManager) _context.getSystemService(Context.WINDOW_SERVICE);
            int screenWidth = wm.getDefaultDisplay().getWidth();
            ViewGroup.LayoutParams lp = viewHolder.showDress.getLayoutParams();
            lp.width = screenWidth;
            lp.height = LayoutParams.WRAP_CONTENT;
            viewHolder.showDress.setLayoutParams(lp);
相關文章
相關標籤/搜索