安卓屏幕适配
自定义一个MyRelativeLayout.java控件
package com.example.administrator.mywb;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
public class MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context);
}
//这个类不能删除的
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MyRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
float scalex = UIUtils.getInstance(getContext()).getHorValue();//UI操作,取得x轴的缩放
float scaley = UIUtils.getInstance(getContext()).getHorValue();//UI操作,取得y轴的缩放
int count = this.getChildCount();
for(int i = 0; i<count; i++){
View child = this.getChildAt(i);
LayoutParams layoutParams = (LayoutParams)child.getLayoutParams();
layoutParams.width = (int)(layoutParams.width*scalex);
layoutParams.height = (int)(layoutParams.height*scaley);
layoutParams.leftMargin = (int)(layoutParams.leftMargin*scalex;
layoutParams.rightMargin = (int)(layoutParams.rightMargin*scalex);
layoutParams.topMargin = (int)(layoutParams.topMargin*scaley);
layoutParams.bottomMargin = (int)(layoutParams.bottomMargin*scaley);
}
}
}
在XML中将LinearLayout格式修改为MyRelativeLayout.java控件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.MyRelativeLayout //改这里
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:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/tv"
android:layout_width="1040px"
android:layout_height="80px"
android:layout_marginLeft="20px"
android:layout_marginTop="50px"
android:layout_marginRight="20px"
android:backgroud="#f00"
android:gravity="center" />
</android.support.constraint.MyRelativeLayout> //改这里