50个Android开发技巧(01 好好利用layout_weight属性)
2015-11-24 11:05
591 查看
问题:如何将一个Button放置在布局中间并将其宽度设为其parent的50%?
分析:问题想要达到的效果应该是这样:
(原文地址:
http://blog.csdn.net/vector_yi/article/details/24397733)
这看起来不难,但很多开发者并不知道达到这样效果的最佳方法。
解决:在此我们将weightSum属性与layout_weight属性一起利用。
[html]
view plain
copy
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:background= "#ffffff"
android:gravity= "center"
android:orientation= "horizontal"
android:weightSum= "1" ><!--1.添加android:weightSum属性-->
<Button
android:layout_width ="0dp"<!--2.将Button的layout_width设为0dp-->
android:layout_height ="wrap_content"
android:layout_weight ="0.5"<!--3.确保其占用了50%的可用空间-->
android:text ="@string/activity_main_click_me" />
</LinearLayout>
可以注意到,在第2步将Button的layout_width设为了0dp,会不会与layout_weight有冲突?答案是不会:
一个控件的宽度是这样计算出来的:
Widget's width + Widget's weight*Parent's width/Parent's weightSum
分析:问题想要达到的效果应该是这样:
(原文地址:
http://blog.csdn.net/vector_yi/article/details/24397733)
这看起来不难,但很多开发者并不知道达到这样效果的最佳方法。
解决:在此我们将weightSum属性与layout_weight属性一起利用。
[html]
view plain
copy
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:background= "#ffffff"
android:gravity= "center"
android:orientation= "horizontal"
android:weightSum= "1" ><!--1.添加android:weightSum属性-->
<Button
android:layout_width ="0dp"<!--2.将Button的layout_width设为0dp-->
android:layout_height ="wrap_content"
android:layout_weight ="0.5"<!--3.确保其占用了50%的可用空间-->
android:text ="@string/activity_main_click_me" />
</LinearLayout>
可以注意到,在第2步将Button的layout_width设为了0dp,会不会与layout_weight有冲突?答案是不会:
一个控件的宽度是这样计算出来的:
Widget's width + Widget's weight*Parent's width/Parent's weightSum
相关文章推荐
- Android VideoView简单播放视频
- android 常见分辨率(mdpi、hdpi 、xhdpi、xxhdpi )及屏幕适配注意事项
- Android开发技巧——自定义控件之自定义属性
- Android开发技巧——自定义控件之自定义属性
- AndroidStudio配置SVN以及使用代码管理
- Android技术博客收藏(持续更新)
- Android开发进阶系列(八) 界面美化之自定义弹出框
- android使用获取所有应用的资源id和uri
- Android-在手机本地保存数据和读取数据
- Android Studio 使用Gradle在Terminal终端用命令打包
- Android的四种启动模式(launchModel)
- Android开源库
- Android性能优化之常见的内存泄漏
- notification的几种使用方法
- Android-Fragment动态例子
- Android开发进阶系列(七) 使用数据库
- Android VideoView简单播放视频
- Android res/raw文件以及raw与res/assets异同
- Android学习----ADB
- 传智播客Android课程与安卓6.0发布会同步更新