如何以編程方式設置ImageView
的寬度和高度? 編程
這個簡單的方法來完成你的任務: app
setContentView(R.id.main); ImageView iv = (ImageView) findViewById(R.id.left); int width = 60; int height = 60; LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height); iv.setLayoutParams(parms);
另外一種方法,若是你想給出屏幕尺寸的高度和寬度,那麼使用下面的代碼: this
setContentView(R.id.main); Display display = getWindowManager().getDefaultDisplay(); ImageView iv = (LinearLayout) findViewById(R.id.left); int width = display.getWidth(); // ((display.getWidth()*20)/100) int height = display.getHeight();// ((display.getHeight()*30)/100) LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height); iv.setLayoutParams(parms);
但願充分利用你。 spa
image_view.getLayoutParams().height
以像素爲單位返回高度值。 您須要先獲取屏幕尺寸才能正確設置值。 code
Display display = context.getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); int screen_height = outMetrics.heightPixels; int screen_width = outMetrics.widthPixels;
得到屏幕尺寸後,能夠使用適當的邊距設置圖像視圖寬度和高度。 對象
view.getLayoutParams().height = screen_height - 140; view.getLayoutParams().width = screen_width - 130 ;
動態設置按鈕的最佳和最簡單的方法是 get
Button index=new Button(this); int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics()); int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());
上述高度和寬度以像素爲單位px 。 45是dp的高度,42是dp的寬度。 io
index.setLayoutParams(new <Parent>.LayoutParams(width, height));
所以,例如,若是您將按鈕放在TableLayout中的TableRow中,則應將其設置爲TableRow.LayoutParams bug
index.setLayoutParams(new TableRow.LayoutParams(width, height));
若是須要將width或height設置爲match_parent
(與其父級同樣大)或wrap_content
(大到足以適合其內部內容),則ViewGroup.LayoutParams
具備如下兩個常量: 方法
imageView.setLayoutParams( new ViewGroup.LayoutParams( // or ViewGroup.LayoutParams.WRAP_CONTENT ViewGroup.LayoutParams.MATCH_PARENT, // or ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT ) );
或者你能夠像在Hakem Zaied的回答中那樣設置它們:
imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT; //...
只需建立一個LayoutParams對象並將其分配給您的imageView
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150); imageView.setLayoutParams(params);