簡體   English   中英

如何為 ImageView 設置LayoutParams()?

[英]How do you setLayoutParams() for an ImageView?

我想為ImageView設置LayoutParams但似乎找不到正確的方法。

我只能在 API 中找到各種ViewGroups的文檔,而不是ImageView 然而ImageView似乎有這個功能。

此代碼不起作用...

myImageView.setLayoutParams(new ImageView.LayoutParams(30,30));

我該怎么做?

您需要設置ImageView所在的ViewGroup的LayoutParams。例如,如果您的ImageView在LinearLayout內,則創建一個

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

這是因為它是View的父級,需要知道要分配給View的大小。

舊線程,但我現在有同樣的問題。 如果有人遇到此問題,他可能會找到以下答案:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

僅當將ImageView作為子視圖添加到LinearLayout時,此方法才有效。 如果將其添加到RelativeLayout中,則需要調用:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

如果要更改現有ImageView的布局,則應該能夠簡單地獲取當前的LayoutParams,更改寬度/高度,然后再將其設置回:

android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);

我不知道這是否是您的目標,但如果是,那可能是最簡單的解決方案。

ImageView從使用ViewGroup.LayoutParams的View獲取setLayoutParams。 如果使用它,在大多數情況下它將崩潰,因此您應該使用View.class中的getLayoutParams()。 這將繼承ImageView的父視圖,並將始終運行。 您可以在此處確認: ImageView擴展視圖

假設您將ImageView定義為“ image_view ”,並將width / height int定義為“ thumb_size”

最好的方法是

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

為了不丟失rest的參數,需要做如下圖:

Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.checked, null);    
preview.setImageDrawable(drawable);
ViewGroup.LayoutParams layoutParams = preview.getLayoutParams();
layoutParams.width = 100;
layoutParams.height = 98;
preview.setLayoutParams(layoutParams);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM