Android开发技巧一--weight属性实现视图的居中(半)显示
2015-09-25 13:54
225 查看
面试时,一位面试官问到:“如果我想讲按钮居中显示,并且占据其父视图宽度的一半,应该怎么做到呢?”即实现这种效果:
我们使用weightSum属性和layout_weight属性实现这一要求:
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="1" >
<Button
android:id="@+id/btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="翻 译"
android:layout_weight="0.5" />
</LinearLayout>
其中有三个重要的设定
1.设定LinearLayout的android:weightSum属性值为1,表示其内部所有子视图的weight比例总和为1;
2.而LinearLayout中只有唯一的一个子视图Button,因此Button的android:layout_weight="0.5;
3.要想weight属性在水平方向上起作用,那么设置layout_weight的宽度为0dp。
我们使用weightSum属性和layout_weight属性实现这一要求:
[html] view plaincopy
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="center"
android:weightSum="1" >
<Button
android:id="@+id/btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="翻 译"
android:layout_weight="0.5" />
</LinearLayout>
其中有三个重要的设定
1.设定LinearLayout的android:weightSum属性值为1,表示其内部所有子视图的weight比例总和为1;
2.而LinearLayout中只有唯一的一个子视图Button,因此Button的android:layout_weight="0.5;
3.要想weight属性在水平方向上起作用,那么设置layout_weight的宽度为0dp。
相关文章推荐
- Android资源汇总
- Android 如何全局获取Context
- Android AIDL
- Android开发艺术探索读书笔记(二)
- android的事件处理
- Android模拟器内安装应用
- Android Log等级的介绍
- Android apk文件资源混淆原理及实现
- Android 拍照和相册选图 版本兼容
- Androida规划nt打包
- 完美解决Android SDK Manager无法更新
- 支持群聊+语音聊天+高仿QQ源码下载 (android前端+JAVA后台+spark<windows版聊天>)方便集成到自己系统
- Android NDK环境搭建及调用JNI的简单步骤
- Android平台下的JNI开发
- 百度地图 Android SDK - Hello Baidu Map
- MPAndroidChart的具体属性方法(二)
- [Android Studio 权威教程]断点调试和高级调试
- Android开发环境搭建教程
- Android SQLiteDatabase的使用模板
- Android(Fragment和Activity之间通信)