脚本宝典收集整理的这篇文章主要介绍了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
>"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
所以我们需要做的就是在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中的代码段延迟到测量结束后才运行。
以上是脚本宝典为你收集整理的Android动态设置控件长宽比的几种常见方法全部内容,希望文章能够帮你解决Android动态设置控件长宽比的几种常见方法所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。