以编程方式设置ImageView的宽度和高度?

如何以编程方式设置ImageView的宽度和高度? 编程


#1楼

这个简单的方法来完成你的任务: 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


#2楼

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 ;

#3楼

动态设置按钮的最佳和最简单的方法是 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));

#4楼

若是须要将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;
//...

#5楼

只需建立一个LayoutParams对象并将其分配给您的imageView

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150);
imageView.setLayoutParams(params);
相关文章
相关标签/搜索