Android principle--Dynamic code layout

Source: Internet
Author: User

Dynamic Code Layout
    1. How to add a code layout
    2. Problems with code layout considerations
    3. Performance comparison of code layout and XML layout
How to add a code layout

For example-- simple layout linearlayout

LinearLayout llayout = new LinearLayout (mcontext);Llayout. SetOrientation(LinearLayout. VERTICAL);LinearLayout. LayoutparamsLayoutparams = new LinearLayout. Layoutparams(LinearLayout. Layoutparams. MATCH_parent, LinearLayout. Layoutparams. MATCH_parent);Llayout. Setlayoutparams(Layoutparams);Button btn = New button (Mcontext);Dt. SetText("This is button");Dt. setpadding(8,8,8,8);Btn. Setlayoutparams(LP);Llayout. AddView(BTN);This is the layout Setcontentview (llayout) set in the activity's OnCreate ();Btn. Setonclicklistener(New View. Onclicklistener() {@Override public void OnClick (View v) {Toast. Maketext(Mcontext,"This is dynamic activity", Toast. LENGTH_long). Show();}        });

Another example-- complex layout relativelayout
Difficulty: Handling the relative position relationship of child controls

Parent control Relativelayout mylayout = new Relativelayout (this);Mylayout. SetBackgroundColor(Color. BLUE); Two child controls Button MyButton = New button (this);EditText myedittext = new EditText (this);Focus: Generate the corresponding ID MyButton. SetId(Generateviewid ());Myedittext. SetId(Generateviewid ());Child control Position Relativelayout. LayoutparamsButtonparams = new Relativelayout. Layoutparams(Relativelayout. Layoutparams. WRAP_content, Relativelayout. Layoutparams. WRAP_content);Buttonparams. AddRule(Relativelayout. CENTER_horizontal);Buttonparams. AddRule(Relativelayout. CENTER_vertical);Relativelayout. LayoutparamsTextparams = new Relativelayout. Layoutparams(Relativelayout. Layoutparams. WRAP_content, Relativelayout. Layoutparams. WRAP_content);Textparams. AddRule(Relativelayout. CENTER_horizontal);Textparams. SetMargins(0,0,0, the);Here's the point Textparams. AddRule(Relativelayout. ABOVE, MyButton. GetId());Add Layout mylayout. AddView(MyButton, Buttonparams);Mylayout. AddView(Myedittext, Textparams);Setcontentview (Mylayout);

The point is that generateViewId() this can be specifically put into the tool class:

    /** * An {@code int} value of May updated atomically. */    Private Static FinalAtomicinteger Snextgeneratedid =NewAtomicinteger (1);/** * Dynamically generated view ID * API level 17 + VIEW.GENERATEVIEWID () generated * API level 17 below need to be generated manually */     Public Static int Generateviewid() {if(Build.VERSION.SDK_INT < Build.version_codes. JELLY_BEAN_MR1) { for(; ; ) {Final intresult = Snextgeneratedid.get ();//aapt-generated IDs has the high byte nonzero, clamp to the range under that.                intNewValue = result +1;if(NewValue >0x00ffffff) NewValue =1;//Roll over to 1, not 0.                if(Snextgeneratedid.compareandset (result, NewValue)) {returnResult }            }        }Else{returnView.generateviewid (); }    }
Problems with code layout considerations
    • Control cannot be reused

      First time Add
      Mlinearlayout.addview (Mtextview, mlayoutparams);
      Second time add
      Mlinearlayout.addview (Mtextview, mlayoutparams);
      We have added two times mtextview. This is not allowed, in the parent class layout, there can only be unique objects and cannot be duplicated.

    • Whether the Id in different activity will be error

      setId(1)it doesn't work to set the ID directly.
      The build ID must be used View.generateViewId()
      My opinion is to build the static tool class to generate the ID
      Questions about whether the ID int is the same or not, is not currently validated

    • Some of the common code

      Textview.settextcolor (0xffff0000);
      Layout.setbackgroundcolor (0x00000000);
      SetOrientation (linearlayout.vertical);
      Setgravity (gravity.center_vertical)
      Setpadding (10, 5, 5, 5);
      SetMargin (8, 0, 0, 0);
      lp.gravity = gravity.center_vertical;
      Lp.topmargin = 5;
      Lp.addrule (relativelayout.center_vertical);
      Lp.addrule (relativelayout.right_of, Id_image_head);

Performance comparison of code layout and XML layout

To test a simple example

Use the code layout as follows:

protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Mcontext = This;LinearLayout llayout = new LinearLayout (mcontext);Llayout. SetOrientation(LinearLayout. VERTICAL);LinearLayout. LayoutparamsLayoutparams = new LinearLayout. Layoutparams(LinearLayout. Layoutparams. MATCH_parent, LinearLayout. Layoutparams. MATCH_parent);Llayout. Setlayoutparams(Layoutparams);TextView TV = new TextView (mcontext);LinearLayout. LayoutparamsLP = new LinearLayout. Layoutparams(LinearLayout. Layoutparams. MATCH_parent, LinearLayout. Layoutparams. WRAP_content);Lp. SetMargins(8,8,8,8);Tv. Setlayoutparams(LP);Tv. SetText("This is TextView");Tv. setpadding(8,8,8,8);Llayout. AddView(TV);Button btn = New button (Mcontext);Btn. SetText("This is button");Btn. setpadding(8,8,8,8);Btn. Setlayoutparams(LP);Setcontentview (Llayout);}

Three measurements average: (23+28 +)/3 = 23.67ms

Using the same XML layout

<linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" match_parent " android:layout_height  =" match_parent " android:orientation  =;     <textview  android:text
      = "This is TextView"  android:layout_width  = "match_parent"  android:layout_height  = "wrap_content"  android:layout_margin  =" 8px " android:padding  =" 8px " />     <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:text="This is button"android:padding="8px"/>                                </linearlayout>

Three measurement averages: (+ + +)/3 = 23.33ms

Conclusion: Although there are few samples, the code layout and the XML layout load time are basically the same and the performance is basically the same.
Insufficient: More complex interface, not tested for the time being.
Idea: Code layout is necessary, if the summary code layout for templates and libraries, the use of generics and reflection, in the interface of reuse and automation, will be more convenient than XML extension.

Android principle--Dynamic code layout

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.