Android Short Tips:FrameLayout子View定位错乱问题
Android应用开发中,FrameLayout让人有爱有憎,爱它的自由,在它内部添加View可以自由布局;也憎它的自由,对于屏幕适配性很差,无法做到通过xml就能完成独立于屏幕参数的布局。
而且,对于低版本的Android环境(低于4.0),FrameLayout中子View的布局会遇到一个错乱的问题。笔者自己在开发中就碰到过,在4.0上布局没问题,但在2.3机型上允许就完全不是想的那样。问题出在哪? Gravity
FrameLayout中的子View,在4.0及以上版本Gravity默认都是左上角,即:
1 Gravity.LEFT | Gravity.TOP
而更低的版本确不是,所以为了保持兼容,必须在xml中或者代码中显示的声明子View的Gravity值。
-
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.scian.handlerdemo.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:gravity="left|top"/> </FrameLayout>
-
代码中
1 public LayoutParams buildGravity(View child) { 2 LayoutParams layoutParams = (LayoutParams) child.getLayoutParams(); 3 layoutParams.gravity = Gravity.LEFT | Gravity.TOP; 4 return layoutParams; 5 }
浙公网安备 33010602011771号