android ImageView 宽度设定,高度自适应
2015-07-06 14:36
387 查看
最近碰到一个需求,要求是在不知道图片宽度和高度的情况下,让图片在指定宽度内充满,同时高度自适应,在网络上查找了一下,也有很多解决方法,后来针对自己的应用,选择了一个修改较小的方案,最后证明效果还是蛮不错的,记录在这里,希望能帮助到有同样需求的人。
好了,言归正传
首先,需要给你的ImageView布局加上android:adjustViewBounds="true"
<ImageView android:id="@+id/test_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
然后,在代码里设置ImageView.最大宽度和最大高度,因为adjustViewBounds属性只有在设置了最大高度和最大宽度后才会起作用
int screenWidth = getScreenWidth(this);
ViewGroup.LayoutParams lp = testImage.getLayoutParams();
lp.width = screenWidth;
lp.height = LayoutParams.WRAP_CONTENT;
testImage.setLayoutParams(lp);
testImage.setMaxWidth(screenWidth);
testImage.setMaxHeight(screenWidth * 5); 这里其实可以根据需求而定,我这里测试为最大宽度的5倍
ok,接下来,再按照常规方法加载图片就会得倒预期的效果了,需要的同学可以试试,good luck.
好了,言归正传
首先,需要给你的ImageView布局加上android:adjustViewBounds="true"
<ImageView android:id="@+id/test_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_launcher" />
然后,在代码里设置ImageView.最大宽度和最大高度,因为adjustViewBounds属性只有在设置了最大高度和最大宽度后才会起作用
int screenWidth = getScreenWidth(this);
ViewGroup.LayoutParams lp = testImage.getLayoutParams();
lp.width = screenWidth;
lp.height = LayoutParams.WRAP_CONTENT;
testImage.setLayoutParams(lp);
testImage.setMaxWidth(screenWidth);
testImage.setMaxHeight(screenWidth * 5); 这里其实可以根据需求而定,我这里测试为最大宽度的5倍
ok,接下来,再按照常规方法加载图片就会得倒预期的效果了,需要的同学可以试试,good luck.
相关文章推荐
- android window 属性
- MTP in Android
- android crash 日志保存
- android 5.0 support
- Android源码之DeskClock (一)
- android 删除SD卡或手机的缓存图像和文件夹
- Android studio 快捷键
- Android仿QQ中的“我的空间”做出ScrollView滑动修改标题栏颜色操作
- Android Studio使用备忘
- 分享45个android实例源码
- android 开发框架
- 使用Kotlin开发Android应用(II):创建新工程
- Android 自定义控件初级 多层按钮旋转控件
- Android动态加载(插件化)基本原理总结
- 使用Kotlin开发Android应用(I):简介
- Kotlin在Android工程中的应用
- 学习android编程之路(1)— 环境变量配置
- Xamarin.Android开发实践(十一)
- Hibernate的优缺点
- android ListView隐藏FooterView(headerView)