Android screen adaptation
I. Screen adaptation tool
Public class MultiScreenTool {
Static Activity;
Public DisplayMetrics displayMetrics = null;
Public int defaultX = 0;
Public int defaultY = 0;
Public float defaultDensity = 1.5f;
Public float nowDensity = 0;
Private static MultiScreenTool instanceVertical = null;
Private static MultiScreenTool instanceHorizontal = null;
Private int tagId;
// Private Map HasAdjust = new HashMap ();
Private String debugId;
Public String getDebugId (){
Return debugId;
}
Public void setDebugId (View view ){
This. debugId = this. getViewCode (view );
}
/**
* This function is called in OnCreate of the first Activity started by the system.
* @ Param act
*/
Private MultiScreenTool (int width, int height, float nowDensity ){
DefaultX = width;
DefaultY = height;
This. nowDensity = nowDensity;
}
/**
* This tool must be called once before singleTonVertical or singleTonHorizontal can be used to obtain an instance.
*
* @ Param act
*/
Public static void init (Activity act ){
DisplayMetrics dm = new DisplayMetrics ();
DisplayMetrics dm2 = new DisplayMetrics ();
If (act = null ){
// If the system fails to marry activity due to an accidental exception, 480*800 of data is used.
Dm. heightPixels = 480;
Dm. widthPixels = 800;
Dm. xdpi = 240f;
Dm. ydpi = 240f;
Dm. density = 1.5f;
Return;
} Else {
Activity = act;
Activity. getWindowManager (). getdefadisplay display (). getMetrics (dm );
}
// The x and y coordinates of the landscape and landscape screens are reversed.
Dm2.heightPixels = dm. widthPixels;
Dm2.widthPixels = dm. heightPixels;
// Log. I ("DisplayMetrics", "activity:" + activity + "dm2.widthPixels:" + dm2.widthPixels + "dm2.heightPixels:" + dm2.heightPixels );
Dm2.xdpi = dm. ydpi;
Dm2.ydpi = dm. xdpi;
Dm2.density = dm. density;
// Log. I ("DisplayMetrics", "xdpi:" + dm2.xdpi + "ydpi:" + dm2.ydpi + "heightPixels:" + dm2.heightPixels + "widthPixels:" + dm2.widthPixels );
InstanceVertical = new MultiScreenTool (Constant. DEFAULT_WIDTH, Constant. DEFAULT_HEIGHT, dm. density );
InstanceHorizontal = new MultiScreenTool (Constant. DEFAULT_HEIGHT, Constant. DEFAULT_WIDTH, dm. density );
If (dm. widthPixels <dm. heightPixels ){
// Current portrait Screen
InstanceVertical. displayMetrics = dm;
InstanceHorizontal. displayMetrics = dm2;
} Else {
// Landscape Screen
InstanceHorizontal. displayMetrics = dm;
InstanceVertical. displayMetrics = dm2;
}
InstanceVertical. tagId = act. getResources (). getIdentifier ("view_tag_id", "id", act. getPackageName ());
InstanceHorizontal. tagId = act. getResources (). getIdentifier ("view_tag_id", "id", act. getPackageName ());
}
/**
* Do not use new in other places. Instead, call this function to obtain the instance.
*
* @ Return
*/
Public static MultiScreenTool singleTonVertical (){
/*
* If (instanceVertical = null) {System. out. println (
* "Error. Before using MultiScreenTool. singleTonVertical, call MultiScreenTool. Init initialization, which only needs to be called once. "
*);
*}
*/
If (instanceVertical = null ){
MultiScreenTool. init (Constant. currentActivity );
}
Return instanceVertical;
}
/**
* Do not use new in other places. Instead, call this function to obtain the instance.
*
* @ Return
*/
Public static MultiScreenTool singleTonHolizontal (){
/*
* If (instanceHorizontal = null) {System. out. println (
* "Error. Before using MultiScreenTool. instanceHorizontal, call MultiScreenTool. Init initialization, which only needs to be called once. "
*);
*}
*/
If (instanceHorizontal = null ){
MultiScreenTool. init (Constant. currentActivity );
}
Return instanceHorizontal;
}
/**
* Obtain the pixel value px in the X direction of the screen.
*
* @ Return
*/
Public int getScreenXDp (){
// Density = px/dp is correct
Return displayMetrics. widthPixels;
}
/**
* Pixel value px in the Y direction of the screen
*
* @ Return
*/
Public int getScreenYDp (){
Return displayMetrics. heightPixels;
}
/**
* Enter a value in the X direction and return a adjusted px value that adapts to multiple screens.
*
* @ Param xInPx
* Px value in the X direction
* @ Return: Applicable to the pixel value px of multiple screens
*/
Public int adjustX (int xInPx ){
Int ret = (int) (xInPx * displayMetrics. widthPixels/this. defaultX * this. defaultDensity/this. nowDensity + 0.5f );
If (ret> displayMetrics. widthPixels ){
Ret = displayMetrics. widthPixels;
}
Return ret;
}
/**
* Enter a value in the X direction and return a adjusted px value that adapts to multiple screens.
*
* @ Param xInPx
* Px value in the X direction
* @ Return: Applicable to the pixel value px of multiple screens
*/
Private float adjustXInFloat (float xInPx ){
Float ret = xInPx * displayMetrics. widthPixels/this. defaultX * this. defaultDensity/this. nowDensity + 0.5f;
If (ret> displayMetrics. widthPixels ){
Ret = displayMetrics. widthPixels;
}
Return ret;
}
/**
* Enter a value in the Y direction and return a adjusted px value that adapts to multiple screens.
*
* @ Param yInPx
* Px value in the Y direction
* @ Return: Applicable to the pixel value px of multiple screens
*/
Public int adjustY (int yInPx ){
Int ret = (int) (yInPx * displayMetrics. heightPixels/this. defaultY * this. defadendensity/this. nowDensity + 0.5f );
If (ret> displayMetrics. heightPixels ){
Ret = displayMetrics. heightPixels;
}
Return ret;
}
/**
* Enter a value in the X direction and return a adjusted px value that adapts to multiple screens.
*
* @ Param xInPx
* Px value in the X direction
* @ Return: Applicable to the pixel value px of multiple screens
*/
Public int adjustXIgnoreDensity (int xInPx ){
Int ret = (int) (xInPx * displayMetrics. widthPixels/this. defaultX );
If (ret> displayMetrics. widthPixels ){
Ret = displayMetrics. widthPixels;
}
Return ret;
}
/**
* Enter a value in the Y direction and return a adjusted px value that adapts to multiple screens.
*
* @ Param yInPx
* Px value in the Y direction
* @ Return: Applicable to the pixel value px of multiple screens
*/
Public int adjustYIgnoreDensity (int yInPx ){
Int ret = (int) (yInPx * displayMetrics. heightPixels/this. defaultY );
If (ret> displayMetrics. heightPixels ){
Ret = displayMetrics. heightPixels;
}
Return ret;
}
Public void adjustView (View view ){
AdjustView (view, true );
}
/**
* Adjust the position and size of a View to fit multiple screens
*
* @ Param view
* @ Param addOnHierarchyChangeListener whether to add the UI change listener
*/
Public void adjustView (View view, boolean addOnHierarchyChangeListener ){
If (view. getLayoutParams () = null ){
// Log. I ("MultiScreenTool", "Error: MultiScreenTool. adjustView: parameter view. getLayoutParams () = null. view should not be called after being added to layout. ");
Return;
}
// If (this. getDebugId ()! = Null & this. getDebugId (). equals (getViewCode (view ))){
/// Log. I ("MultiScreenTool", "stop here ");
//}
If (view instanceof ViewGroup ){
ViewGroup vg = (ViewGroup) view;
For (int I = 0; I <vg. getChildCount (); ++ I ){
AdjustView (vg. getChildAt (I), addOnHierarchyChangeListener );
}
// All
If (addOnHierarchyChangeListener ){
Vg. setOnHierarchyChangeListener (new HierarchyChangeListener (this ));
}
}
// System. out. printf (view. hashCode () + "");
// If (hasAdjust. get (getViewCode (view ))! = Null ){
// Return;
//} Else {
// HasAdjust. put (getViewCode (view), true );
// Log. I ("MultiScreenTool", "hasAdjust. size ():" + hasAdjust. size ());
//}
// If (view. getTag (tagId )! = Null ){
// Return;
//} Else {
// View. setTag (tagId, true );
//}
Int tmp = 0;
// Boolean hasAdjust = false;
// Adjust the layout Parameter
If (view. getLayoutParams () instanceof ViewGroup. MarginLayoutParams ){
ViewGroup. MarginLayoutParams lp = (ViewGroup. MarginLayoutParams) view. getLayoutParams ();
// Log. I ("MultiScreenTool", "density =" + displayMetrics. density + "width =" + lp. width + "height =" + lp. height + "leftMargin ="
// + Lp. leftMargin + "topMargin =" + lp. topMargin + "bottomMargin =" + lp. bottomMargin + "rightMargin =" + lp. rightMargin );
// View. getd
If (lp. height> 0 ){
Lp. height = this. adjustY (int) (lp. height ));
// HasAdjust = true;
} Else if (lp. height = RelativeLayout. LayoutParams. WRAP_CONTENT ){
Tmp = view. getMeasuredHeight ();
If (tmp! = 0 ){
Lp. height = this. adjustY (tmp );
}
}
If (lp. width> 0 ){
Lp. width = this. adjustX (int) (lp. width ));
// HasAdjust = true;
} Else if (lp. width = RelativeLayout. LayoutParams. WRAP_CONTENT ){
Tmp = view. getMeasuredWidth ();
If (tmp! = 0 ){
Lp. width = this. adjustX (tmp );
}
}
Lp. leftMargin = this. adjustX (int) (lp. leftMargin ));
Lp. topMargin = this. adjustY (int) (lp. topMargin ));
Lp. bottomMargin = this. adjustY (int) (lp. bottomMargin ));
Lp. rightMargin = this. adjustX (int) (lp. rightMargin ));
// Log. I ("MultiScreenTool", "width =" + lp. width + "height =" + lp. height + "leftMargin =" + lp. leftMargin + "topMargin =" + lp. topMargin
// + "BottomMargin =" + lp. bottomMargin + "rightMargin =" + lp. rightMargin );
View. setLayoutParams (lp );
// Adjust the padding Parameter
View. setPadding (this. adjustX (view. getPaddingLeft (), this. adjustY (view. getPaddingTop (), this. adjustX (view. getPaddingRight (), this. adjustY (view. getPaddingBottom ()));
} Else if (view. getLayoutParams () instanceof ViewGroup. LayoutParams ){
ViewGroup. LayoutParams lp = (ViewGroup. LayoutParams) view. getLayoutParams ();
// View. getd
If (lp. height> 0 ){
Lp. height = this. adjustY (int) (lp. height ));
// HasAdjust = true;
} Else if (lp. height = RelativeLayout. LayoutParams. WRAP_CONTENT ){
Tmp = view. getMeasuredHeight ();
If (tmp! = 0 ){
Lp. height = this. adjustY (tmp );
}
}
If (lp. width> 0 ){
Lp. width = this. adjustX (int) (lp. width ));
// HasAdjust = true;
} Else if (lp. width = RelativeLayout. LayoutParams. WRAP_CONTENT ){
Tmp = view. getMeasuredWidth ();
If (tmp! = 0 ){
Lp. width = this. adjustX (tmp );
}
}
View. setLayoutParams (lp );
// Adjust the padding Parameter
View. setPadding (this. adjustX (view. getPaddingLeft (), this. adjustY (view. getPaddingTop (), this. adjustX (view. getPaddingRight (), this. adjustY (view. getPaddingBottom ()));
} Else {
// Log. I ("MultiScreenTool", "MultiScreenTool: The following layoutparams () type is not processed" + view. getLayoutParams (). getClass (). toString ());
}
// If the image is not adjusted, the background image is mostly set and the width and height of the view cannot be reached. Special processing is performed here.
// If (view instanceof ImageView & hasAdjust = false ){
// Int bgWidth = view. getBackground (). getMinimumWidth ();
// BgWidth = this. adjustX (bgWidth );
// Int bgHight = view. getBackground (). getMinimumHeight ();
// BgHight = this. adjustY (bgHight );
// ViewGroup. LayoutParams rlp = view. getLayoutParams ();
// Rlp. height = bgHight;
// Rlp. width = bgWidth;
// View. setLayoutParams (rlp );
//}
// Adjust the font size
If (view instanceof android. widget. TextView ){
Android. widget. TextView TV = (android. widget. TextView) view;
Float textSizeInPx = TV. getTextSize ();
TextSizeInPx = this. adjustXInFloat (textSizeInPx );
TV. setTextSize (TypedValue. COMPLEX_UNIT_PX, textSizeInPx );
}
}
/**
* Clear the registration information of a view and all its subviews from the registration form. The registration information can be adjusted only when the subsequent window is reinitialized.
*
* @ Param view
*/
Public void unRegisterView (View view ){
/// If (this. getDebugId ()! = Null & this. getDebugId (). equals (getViewCode (view ))){
/// Log. I ("MultiScreenTool", "stop here ");
////}
/// If (view instanceof ViewGroup ){
/// ViewGroup vg = (ViewGroup) view;
/// For (int I = 0; I <vg. getChildCount (); ++ I ){
/// UnRegisterView (vg. getChildAt (I ));
////}
////}
///// System. out. printf (view. getId () + "");
///// If (hasAdjust. get (getViewCode (view ))! = Null ){
///// HasAdjust. remove (getViewCode (view ));
//////}
////
//// View. setTag (tagId, null );
// Return;
}
Private String getViewCode (View view ){
String code = view. hashCode () + "_" + view. getId ();
Return code;
}
/**
* Adjust the ImageView. Generally, the width and height of the image are not obtained in this ImageView. Therefore, the image cannot be adjusted using adjustView.
* @ Param view
*/
Public ViewGroup. LayoutParams getAdjustLayoutParamsForImageView (ImageView view ){
If (view. getTag (tagId )! = Null ){
Return view. getLayoutParams ();
} Else {
View. setTag (tagId, true );
}
Int bgWidth = view. getBackground (). getMinimumWidth ();
BgWidth = this. adjustXIgnoreDensity (bgWidth );
Int bgHight = view. getBackground (). getMinimumHeight ();
BgHight = this. adjustYIgnoreDensity (bgHight );
ViewGroup. LayoutParams rlp = new ViewGroup. LayoutParams (bgWidth, bgHight );
Return rlp;
}
/**
* Check whether the screen size is changed (for some flat panels, the height and original width are different after horizontal and vertical conversion)
* @ Param act: activity called
*/
// Public void checkWidthAndHeight (Activity act ){
Public void checkWidthAndHeight (){
DisplayMetrics dm = new DisplayMetrics ();
Activity. getWindowManager (). getdefadisplay display (). getMetrics (dm );
If (dm. widthPixels> dm. heightPixels ){
If (this. displayMetrics. widthPixels> this. displayMetrics. heightPixels ){
This. displayMetrics. widthPixels = dm. widthPixels;
This. displayMetrics. heightPixels = dm. heightPixels;
} Else {
This. displayMetrics. widthPixels = dm. heightPixels;
This. displayMetrics. heightPixels = dm. widthPixels;
}
} Else {
If (this. displayMetrics. widthPixels> this. displayMetrics. heightPixels ){
This. displayMetrics. widthPixels = dm. heightPixels;
This. displayMetrics. heightPixels = dm. widthPixels;
} Else {
This. displayMetrics. widthPixels = dm. widthPixels;
This. displayMetrics. heightPixels = dm. heightPixels;
}
}
}
}
(Note: Here Constant is a class that saves the current activity Constant)
Ii. Usage
1. initialization can be performed in onCreate () of BaseActivity.
Public class BaseActivity extends Activity {
Protected MultiScreenTool mst = null;
Public Handler handler;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
Constant. currentActivity = this;
// Determine the portrait screen of the horizontal screen and initialize the multi-screen adaptation tool
If (getRequestedOrientation () = ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE ){
Mst = MultiScreenTool. singleTonHolizontal ();
} Else {
Mst = MultiScreenTool. singleTonVertical ();
}
Mst. checkWidthAndHeight ();
ActivityPool. push (this );
}
@ Override
Protected void onStart (){
Super. onStart ();
Constant. currentActivity = this;
If (! GetClass (). equals (StartActivity. class) {// whether the page is started
Mst. checkWidthAndHeight ();
}
}
@ Override
Protected void onResume (){
Super. onResume ();
Constant. currentActivity = this;
DCAgent. onResume (this );
// Obtain the screen resolution
DisplayMetrics dm = new DisplayMetrics ();
GetWindowManager (). getDefaultDisplay (). getMetrics (dm );
If (dm. widthPixels> dm. heightPixels ){
Constant. SCREEN_WIDTH = dm. widthPixels;
Constant. SCREEN_HEIGHT = dm. heightPixels;
} Else {
Constant. SCREEN_WIDTH = dm. heightPixels;
Constant. SCREEN_HEIGHT = dm. widthPixels;
}
}
@ Override
Protected void onPause (){
Super. onPause ();
DCAgent. onPause (this );
}
@ Override
Protected void onDestroy (){
Super. onDestroy ();
Mst = null;
}
@ Override
Public boolean onKeyDown (int keyCode, KeyEvent event ){
Switch (keyCode ){
Default:
Break;
}
Return super. onKeyDown (keyCode, event );
}
Public void finishSelf (){
ActivityPool. remove (this );
This. finish ();
}
}
(Note: This is just an example. You only need to select mst-related content)
2. Call the mst object for adjustment.
RelativeLayoutmainRelativeLayout = (RelativeLayout) findViewById (R. id. main_relativeLayout );
Mst. adjustView (mainRelativeLayout );
(Main_relativeLayout is the layout for screen adaptation)