match_parent = -1多Dpi适配布局消失
android源码中match_parent
可见FILL_PARENT=-1、MATCH_PARENT=-1、WRAP_CONTENT =-2
他们都为负数,数据类型都为整数
布局中调用
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.demo.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:id="@+id/test"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Hello World!" />
</FrameLayout>
要确保布局的灵活性并适应各种尺寸的屏幕,应使用 “wrap_content” 和 “match_parent” 控制某些视图组件的宽度和高度。
使用 “wrap_content”,系统就会将视图的宽度或高度设置成所需的最小尺寸以适应视图中的内容,而 “match_parent”(在低于 API 级别 8 的级别中称为 “fill_parent”)则会展开组件以匹配其父视图的尺寸。
如果使用 “wrap_content” 和 “match_parent” 尺寸值而不是硬编码的尺寸,视图就会相应地仅使用自身所需的空间或展开以填满可用空间。此方法可让布局正确适应各种屏幕尺寸和屏幕方向。
适配多Dpi和多显示模式
private void init() {
mText = (TextView) findViewById(R.id.test);
ViewGroup.LayoutParams lp = mText.getLayoutParams();
Log.d(TAG, "mText.getLayoutParams():width=" + lp.width);
lp.width = lp.width * (400 / 240);
Log.d(TAG, "mText.getLayoutParams():width=" + lp.width);
mText.setText("\n" + getDisplay() + "\n");
}
private String getDisplay() {
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
return " 手机屏幕的分辨率的大小是:" + dm.widthPixels + "*" + dm.heightPixels
+ "\n 屏幕密度(0.75 / 1.0 / 1.5) " + dm.density +
"\n 屏幕密度DPI(120 / 160 / 240) " + dm.densityDpi;
}
进行dpi适配时lp.width = lp.width * (400 / 240);会对布局宽高进行放缩,由于 (400 / 240)这个一般是density/realDpi值,这个值在(-∞,-1]&[1,+∞)时道没有什么影响
问题1:当(-1,1)之间,布局就会消失
原因:由于lp.width = match_parent = -1,且lp.width为整数类型,强制换换为整数,最后乘积 lp.width * (213 / 240) = 0;问题2:当[2,+∞)之间,布局相当于设置为wrap_content
问题3:在(-∞,-1]之间布局虽然不会消失,但是宽高就是固定的数字;布局会严重的变形