android 开发的时候怎么动态设置控件宽高

android 开发的时候怎么动态设置控件宽高,第1张

//设置控件高度为宽度的一半

//screenWidth 为屏幕的宽度

//View为你要设置的控件

//LinearLayout.LayoutParams 为这个控件外部的布局

LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) View.getLayoutParams()

layoutParams.height = screenWidth / 2

一、方法

使用getLayoutParams() 和setLayoutParams()方法

二、示例代码

LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) aaa.getLayoutParams()

// 取控件aaa当前的布局参数

linearParams.height = 365 // 当控件的高强制设成365象素

aaa.setLayoutParams(linearParams)// 使设置好的布局参数应用到控件aaa

三、原理

a)getLayoutParams()和setLayoutParams()都是控件基类view的public方法,在外部也可以直接调用。

b)由于LayoutParams一般是在加入容器中设置的,所以容易混淆所指定的布局属性究竟是保存在容器中,还是控件本身的属性,答案是控件本身。但是在设置时还是要注意布局属性与容器种类密切相关。

<ImageView

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:background="@drawable/ic_launcher" />

宽度和高度使用fill_parent (填充父窗体)

fill_parent 可以使控件充满父控件,也就是你说的自动使用图片控件外的控件大小。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11026122.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存