邁出第一步:自適應高度的ImageView(AutoHeightImageView)


這個博客注冊很久了,可是一直都沒有勇氣來寫一點東西。今天解決了一個讓我糾結很久的問題,於是,我決定開始我的博客生涯,希望我能堅持下去。

不知道是不是只有我遇到了這個問題,在ListView中顯示圖片,當需求是顯示的圖片寬度最寬,但是高度自適應時。在xml里設ImageView的高度屬性是不能解決問題的。網上我也找了下方法。有說設 Android:adjustViewBounds這個屬性的,它需要設maxheight和maxwidth配合使用,我開始加入的時候,在一些手機上也確實是成功,可是換了個手機之后,發現在不行。也就是說,在android版本這么多,廠商這么多的情況下。它不能保證效果是可以實現。然后也有方法說在設完圖片圖片之后,去根據圖片的寬高比,設控件的高度,我沒有去做代碼的實現,因為我知道它可行,但是不是我想的要。

直接先上代碼吧:

 1 import android.content.Context;
 2 import android.graphics.drawable.Drawable;
 3 import android.util.AttributeSet;
 4 import android.widget.ImageView;
 5 import android.widget.RelativeLayout;
 6 
 7 public class AutoHeightImageView extends ImageView {
 8 
 9     private Drawable mDrawable = null;
10     private static int mWidth = 0;
11 
12     public AutoHeightImageView(Context context, AttributeSet attrs) {
13         super(context, attrs);
14     }
15 
16     public AutoHeightImageView(Context context) {
17         super(context);
18     }
19 
20     public AutoHeightImageView(Context context, AttributeSet attrs, int defStyle) {
21         super(context, attrs, defStyle);
22     }
23 
24     @Override
25     public void setImageDrawable(Drawable drawable) {
26         super.setImageDrawable(drawable);
27         mDrawable = getDrawable();
28         if (mWidth != 0) {
29             setAutoHeight();
30         }
31     }
32 
33     @Override
34     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
35         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
36         if (mWidth == 0) {
37             mWidth = getMeasuredWidth();
38             if (mDrawable != null) {
39                 setAutoHeight();
40             }
41         }
42     }
43 
44     private void setAutoHeight() {
45         float scale = mDrawable.getMinimumHeight() / (float) mDrawable.getMinimumWidth();
46         float height = mWidth * scale;
47         setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) height));
48     }
49 }

 


看完其實是很簡單的東西,實現也就是根據圖片的寬高比來完成,只是我把這些讓到的控件的自定義里實現。說說需要注意的問題吧:在重寫的OnMeasure()方法里,要在調用了super的方法之后,再能得到你在xml里ImageView的寬度,因為我這里高度由寬度決定,所以只能取最初那一次的,OnMeasure()方法會多次調用(沒有去追究原因),這樣,放到ListView里的時間,高度就能自適應了。

弄出來,自己是挺開心的,希望大家有意見和建議多多指出。也希望我能有更的東西分享出來,讓大家幫忙優化,一起提高!

續:自己在復用這個控件的時候,發現在個問題,也又弄清楚了一個問題:

關於這名話的

setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) height));

當我要這個控件用到一個LinearLayout下的時候,異常了,原來這個LayoutParams和它所在父控件有關。不分統一用一個,后改成了

if (getParent() instanceof RelativeLayout) {
  setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) height));
}
if (getParent() instanceof LinearLayout) {
  setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) height));
}

自己根據需要加吧!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM