Android动态设置控件长宽比的几种常见方法

我们在日常的开发中经常需要根据设备的大小来确定控件大小,或者根据控件已知的长宽设置其他控件长宽,这里记录几种常见的方法:

根据设备宽度和长度确定控件大小

例如现在想把某个图片设置成宽度和屏幕宽度一样,长度是宽度的一半
假设img所处布局为LinearLayout

ImageView img = //smth
int width = img.getContext().getResources().getDisplayMetrics().widthPixels;
int height = width * 0.5;
img.setLayoutParams(new LinearLayout.LayoutParams(width , height));
    
根据控件已确定宽度设置长度

现在看下面的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorDivider"
    android:padding="10dp">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:scaleType="fitXY"
        android:id="@+id/imgv_activity"
        android:src="@drawable/default_herald"/>
</RelativeLayout>

此处由于根布局的padding跟设备的大小其实是已知的,所以ImageView的宽度是设备的宽度减去padding的大小,但是实际使用中,如这时候想根据ImageView的实际宽度来设置高度,跟上面的例子一样,如果我能获取到width就好办了,但是经常会发现如果我们调用

ImageView img = //smth
int width = img.getWidth()

得到的width为0,是因为这个函数调用太早,img还没有测量长宽,所以得到的结果是0

参考资料 https://stackoverflow.com/questions/3591784/getwidth-and-getheight-of-view-returns-0/24035591#24035591

所以我们需要做的就是在img测量过后后再去获取width,查看了stackOverflow上的相关问题(上述参考资料链接),可以采用



ImageView img = //smth
img.post(new Runnable() {
        @Override
        public void run() {
            int width = img.getWidth();
            int height = width * 0.5;
            img.setLayoutParams(new LinearLayout.LayoutParams(width , height));
        }
    });
    

其中post方法的作用是,把传入的runnable中的代码段延迟到测量结束后才运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值