Android percent layout and example code _android

Source: Internet
Author: User
Tags static class

Android percent layout

1. Introduction: Compile ' com.android.support:percent:24.0.0 '

2. Point source code can be seen, there are mainly two layout classes Percentframelayout and Percentrelativelayout, a tool class Percentlayouthelper.

3. Point open layout class such as percentrelativelayout source code, you can see the implementation is very simple.

public class Percentrelativelayout extends Relativelayout {private final percentlayouthelper mhelper = new Percentlayo

  Uthelper (this);

    /** omit code such as several line constructs **/@Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//focus on this
    Mhelper.adjustchildren (Widthmeasurespec, Heightmeasurespec);
    Super.onmeasure (Widthmeasurespec, Heightmeasurespec);
    if (Mhelper.handlemeasuredstatetoosmall ()) {super.onmeasure (Widthmeasurespec, Heightmeasurespec); } @Override protected void OnLayout (Boolean changed, int left, int. top, int right, int bottom) {Super.onlayo
    UT (changed, left, top, right, bottom);
  Mhelper.restoreoriginalparams (); public static class Layoutparams extends Relativelayout.layoutparams implements Percentlayouthelper.percentlayo

    Utparams {private Percentlayouthelper.percentlayoutinfo mpercentlayoutinfo;
      Public Layoutparams (Context C, AttributeSet Attrs) {super (C, attrs); MpercentlayoUtinfo = Percentlayouthelper.getpercentlayoutinfo (c, attrs);
      **/@Override public Percentlayouthelper.percentlayoutinfo getpercentlayoutinfo ()/** omitting code such as several lines of construction methods () {
      if (Mpercentlayoutinfo = = null) {Mpercentlayoutinfo = new percentlayouthelper.percentlayoutinfo ();
    return mpercentlayoutinfo; @Override protected void Setbaseattributes (TypedArray A, int widthattr, int heightattr) {percentlayouthe
    Lper.fetchwidthandheight (This, a, widthattr, heightattr);

 }
  }
}

It was in onmeasure and onlayout that some of the methods of Percentlayouthelper were called, and in addition, their layoutparams were defined, and the layoutparams was quite simple.

The key line of code here is in the Onmeasure method, Mhelper.adjustchildren (Widthmeasurespec, Heightmeasurespec); Adjustchildren traverse the child view to set the width and height of the child view, and the Percentlayouthelper inner class Percentlayoutinfo calculated by the value set in the layout file.

public void Adjustchildren (int widthmeasurespec, int heightmeasurespec) {//Calculate available spaces, accounting f Or host ' s paddings int widthhint = View.MeasureSpec.getSize (widthmeasurespec)-Mhost.getpaddingleft ()-Mhost
    . Getpaddingright ();
    int heighthint = View.MeasureSpec.getSize (heightmeasurespec)-mhost.getpaddingtop ()-Mhost.getpaddingbottom (); for (int i = 0, n = mhost.getchildcount (); i < n; i++) {//Traverse child view to set the height view view of the child view = Mhost.getc
      Hildat (i);
      Viewgroup.layoutparams params = View.getlayoutparams ();
      if (DEBUG) {log.d (TAG, "should adjust" + View + "" + params); } if (params instanceof percentlayoutparams) {Percentlayoutinfo info = ((percentlayoutparams) p

        Arams). Getpercentlayoutinfo (); if (info!= null) {if (params instanceof viewgroup.marginlayoutparams) {Info.fillmarginlayoutparam
S (view, (viewgroup.marginlayoutparams) params,                Widthhint, Heighthint);
          else {info.filllayoutparams (params, widthhint, heighthint);

 }
        }
      }
    }
  }

4. How to use the layout: taking Percentrelativelayout as an example

<android.support.percent.percentrelativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
  xmlns:app= "Http://schemas.android.com/apk/res-auto"
  android:layout_width= "Match_parent"
  android: layout_height= "Match_parent"
  android:background= "@color/background_color"
  >

  <textview
    Android:id= "@+id/mian_tab_name"
    android:layout_width= "wrap_content"
    android:layout_height= "WRAP_" Content "
    android:gravity=" center "
    android:textcolor=" "@color/back_green"
    android:textsize= "15SP"
    android:text= "name"
    />

  <imageview
    app:layout_widthpercent= "50%"
    app:layout_ Heightpercent= "50%"
    android:src= "@drawable/ic_launcher_icon"
    android:scaletype= "Fitxy"
    android: layout_below= "@+id/mian_tab_name"
    android:background= "@color/black"
    />

</ Android.support.percent.percentrelativelayout>

Introduce the Xmlns:app namespace, and then app:layout_widthpercent= "50%" to set the percentage of the width high. Quite simple.

5. However, in the use of the process, there may be some other requirements, such as app:layout_widthpercent= "50%", app:layout_heightpercent= "50%" are relative to the screen of the wide-height, What if you want to display a square picture with a width of 50%? This is the time to write:

<imageview
    app:layout_widthpercent= "50%"
    app:layout_aspectratio= 100% "
    android:src=" @drawable Ic_launcher_icon "
    android:scaletype=" Fitxy "
    android:layout_below=" @+id/mian_tab_name "
    android: background= "@color/cs_black"
    />

Using the Layout_aspectratio property, set the App:layout_aspectratio= "100%", layout_aspectratio is the aspect ratio. Do not set the App:layout_heightpercent attribute at this time. Inside the Percentlayouthelper, the source code is as follows:

public void Filllayoutparams (viewgroup.layoutparams params, int widthhint, int heighthint) {//Preserve th
      E original layout params, so we can restore them on the measure step.
      Mpreservedparams.width = Params.width;

      Mpreservedparams.height = Params.height; We assume that Width/height set to 0 means this value was unset. This might is not//necessarily is true, as the user might explicitly set it to 0. However, we use this//information only for the aspect ratio.
      If the user set the aspect ratio attribute,//It means they accept or soon discover that it would be disregarded. Final Boolean widthnotset = (Mpreservedparams.miswidthcomputedfromaspectratio | | mpreservedpa
      Rams.width = = 0 && (widthpercent < 0); Final Boolean heightnotset = (Mpreservedparams.misheightcomputedfromaspectratio | | mpreservedparam

      S.height = = 0 && (heightpercent < 0); If(widthpercent >= 0)
      {params.width = (int) (Widthhint * widthpercent);
      } if (heightpercent >= 0) {params.height = (int) (Heighthint * heightpercent);

           }//This piece of code is critical if the Aspectratio >=0,aspectratio is wide-height ratio if (aspectratio >= 0) {if (Widthnotset) {
          If the width is not set, the height is quasi params.width = (int) (params.height * aspectratio);
          Keep track that we ' ve filled the width of based on the height and aspect ratio.
        Mpreservedparams.miswidthcomputedfromaspectratio = true;
          if (heightnotset) {//If the height is not set, the width is quasi params.height = (int) (params.width/aspectratio);
          Keep track that we ' ve filled the height of based on the width and aspect ratio.
        Mpreservedparams.misheightcomputedfromaspectratio = true; 
      } if (DEBUG) {log.d (TAG, "after Filllayoutparams: (" + Params.width + "," + Params.height + ")");

 }
    }

6. In addition, if we want to define their own percentlinearlayout, the basic can directly change the name, inherited from the LinearLayout is good: public class Percentlinearlayout extends LinearLayout, in imitation of percentrelativelayout inside layoutparams definition of a own layoutparams is good.

But why did the authorities not provide a percentlinearlayout class directly, but only two percentframelayout and percentrelativelayout? Perhaps it is because the linearlayout itself has the right to attribute, with a percent effect.

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.