2017-01-25 32 views
1

我已經創建了一個ImageView的代碼,我希望它的最大尺寸爲24x24dp。但setMaxHeight/Width不起作用。我使用的圖像是一個可繪製的svg,它的大小是40x40dp。ImageView將不服從maxWidth和高度

我也曾嘗試使用imageView.setMinimumHeight/Width

imageView.setLayoutParams(new ViewGroup.LayoutParams((int) getTypedValueInDP(24), (int) getTypedValueInDP(24))); 

沒有任何效果!

在這裏,我創建的ImageView:

 ImageView imageView = new ImageView(context); 
     imageView.setMaxHeight(getTypedValueInDP(20)); 
     imageView.setMaxWidth(getTypedValueInDP(20)); 
     imageView.setImageDrawable(context.getResources().getDrawable(drawable)); 
     imageView.setPadding(left, 0, left, 0); 

,我使用它與一個RelativeLayout的也是這樣的代碼製作:

RelativeLayout toastLayout = new RelativeLayout(context); 
    toastLayout.setBackground(getBLLShape()); 
    toastLayout.addView(getImageView()); 

回答

1

您需要添加到ViewGroup中之前指定的ImageView中的LayoutParams。

ImageView imageView = new ImageView(this); 
imageView.setMaxHeight(getTypedValueInDP(20)); 
imageView.setMaxWidth(getTypedValueInDP(20)); 
imageView.setAdjustViewBounds(true); 
imageView.setImageDrawable(context.getResources().getDrawable(drawable)); 
RelativeLayout.LayoutParams layoutParams = 
    new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
     RelativeLayout.LayoutParams.WRAP_CONTENT); 
imageView.setLayoutParams(layoutParams); 

RelativeLayout toastLayout = new RelativeLayout(this); 
toastLayout.addView(imageView); 
+0

它的工作圖像的能力。但我也試過只是把'imageView.setAdjustViewBounds(true);'和刪除任何與'LayoutParams'相關的代碼,它仍然工作 – Muddz

+0

@Muddz酷。我在此基礎上添加了'setAdjustViewBounds' [post](http://stackoverflow.com/a/9303270/549978)。 – blizzard

+0

有什麼不對。如果'imageView.setMaxWidth(getTypedValueInDP(20));'它會導致作爲'RelativeLayout'的父佈局在屏幕和'ImageView'消失時有一個高度!但是,如果超出maxWidth,它的行爲應該如此,因爲它應該保持不變maxWidth將不會被設置 請參閱此屏幕快照:http://i.imgur.com/lFJoU2C.png – Muddz

-1

如果你的形象和ImageView的具有相同的寬高比。你有沒有嘗試

imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE)

+0

我不能保證它,因爲用戶必須更改的ImageView – Muddz

1

填充似乎搞亂了setMaxWidth()。確保你在兩邊填充的填充不能等於或大於setMaxWidth參數。在你的代碼中,你正在填充左側和右側。所以,變化:

imageView.setMaxWidth(getTypedValueInDP(20)); 

imageView.setMaxWidth(2* left + getTypedValueInDP(20)); 
相關問題