如何在Android程序中以编程方式更改ImageButton的大小

3

我需要程序动态创建几个按钮和图像按钮,但是我不知道如何改变它们的大小。尝试改变左右并没有起作用。

4个回答

5
请使用这个。
LinearLayout.LayoutParams params = button.getLayoutParams();
params.width = 80;
button.setLayoutParams(params);

它应该正常工作


1
你可以尝试这个:

imageView.getLayoutParams().height = 200;//set appropriate sizes
imageView.getLayoutParams().width= 200;
imageView.requestLayout();//this line redraws the imageview again call only after you set the size

0
Here if you want to change the size of the button, you have to change the xml code here it goes.

     <FrameLayout                                        android:layout_width="wrap_content" android:layout_height="wrap_content">           
            <Button     android:id="@+id/saveSearchButton"  android:layout_width="50dp"         android:layout_height="50dp" />
            <ImageView                                      android:layout_width="45dp"         android:layout_height="45dp" android:scaleType="fitXY" android:src="@drawable/ic_menu_save" android:layout_gravity="center"/>
        </FrameLayout>
        <FrameLayout                                        android:layout_width="wrap_content" android:layout_height="wrap_content">           
            <Button     android:id="@+id/clearSearchButton" android:layout_width="50dp"         android:layout_height="50dp" />
            <ImageView                                      android:layout_width="45dp"         android:layout_height="45dp" android:scaleType="fitXY" android:src="@drawable/ic_menu_close_clear_cancel" android:layout_gravity="center"/>

//ImageView Setup
ImageView imageView = new ImageView(this);

//setting height and width of imageview
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

//setting margins around imageimageview
`params.setMargins(10, 10, 10, 10);` //left, top, right, bottom

//adding attributes to the imageview
imageView.setLayoutParams(params);

但这是关于按钮而不仅仅是简单的图像,它还是同样的方式吗? - qwkldmas
我已经包含了XML代码,这将帮助你 @qwkldmas - Deepanshu J bedi

0
imgbtn.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

或者:

imgbtn.setLayoutParams(new LinearLayout.LayoutParams(200, 100));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接