Android dynamically add a way to set layout and controls _android

Source: Internet
Author: User

This example describes the way Android dynamically adds settings and controls. Share to everyone for your reference, specific as follows:

Sometimes we will be on the code side, dynamically setting, adding layouts and controls. Below we look at how to deal with, directly on the code, the code inside the annotation is very clear.

Layout file: Fragment_hot.xml

Description: This department, I used the ScrollView as the basic layout, mainly to achieve a scrolling. Here is not much to say, this you can use any layout can be, here's ID I was in advance defined.

Now there's a layout that I want to see me in the code side, dynamically added code, whether you can append to the back of the existing layout plus, here you can set up their own

<?xml version= "1.0" encoding= "Utf-8"?> <scrollview xmlns:android= "http://schemas.android.com/apk/res/" Android "android:id=" @id/id_stickynavlayout_innerscrollview "android:layout_width=" Match_parent "Android:layout_ height= "Match_parent" > <linearlayout android:id= "@+id/line_fragment_hot_main" android:layout_width= "Match_" Parent "android:layout_height=" match_parent "android:orientation=" vertical "> <linearlayout Android : layout_width= "fill_parent" android:layout_height= "80DP" android:orientation= "Horizontal" > <Linear
        Layout android:layout_width= "0DP" android:layout_height= "70DP" android:layout_weight= "1" > <imageview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an droid:src= "@drawable/desktop_device"/> </LinearLayout> <linearlayout android:layout_width= "0DP" android:layout_height= "70DP "android:layout_weight=" 1 "android:orientation=" vertical "> <textview android:la Yout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "The Peacock city of the suburbs"/> <T Extview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:tex t= "Yan Jiao suburbs"/> <textview android:layout_width= wrap_content "android:layout_height=" Wrap_co Ntent "android:text=" 30,000 to 60,000 "/> <textview android:layout_width=" Wrap_content "an droid:layout_height= "Wrap_content" android:text= "6000 Yuan/M"/> </LinearLayout> <linearlayou T android:layout_width= "0DP" android:layout_height= "70DP" android:layout_weight= "1" Androi D:gravity= "Right" > <textview android:layout_width= "wrap_content" android:layout_height= "
          Wrap_content "android:text= "2 days Left" android:textcolor= "#F97F49" android:textsize= "12DP" android:textstyle= "bo
          LD "android:layout_margintop=" 2DP "/> <textview android:layout_width=" Wrap_content " android:layout_height= "Wrap_content" android:background= "@drawable/rectangle_radius_fen" Android:
          gravity= "Center" android:text= "Regiment" android:textsize= "9DP" android:textcolor= "#ffffff" android:layout_marginright= "5DP" android:layout_marginleft= "2DP"/> </LinearLayout> </li nearlayout> <linearlayout android:layout_width= "fill_parent" android:layout_height= "80DP" Andr oid:orientation= "Horizontal" > <linearlayout android:layout_width= "0DP" android:layout_height= "
          70DP "android:layout_weight=" 1 "> <imageview android:layout_width=" wrap_content " Android:layout_height= "WRap_content "android:src=" @drawable/desktop_device "/> </LinearLayout> <linearlayout Android:layout_width= "0DP" android:layout_height= "70DP" android:layout_weight= "1" Android:orie ntation= "vertical" > <textview android:layout_width= "wrap_content" android:layout_height=
          "Wrap_content" android:text= "The Peacock City of Yan Jiao"/> <textview android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "Yan Jiao suburbs"/> <textview Android:layo Ut_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "30,000 to 60,000"/> <tex Tview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "6000/M"/> </LinearLayout> <linearlayout android:layout_width= "0DP" android:layou
        t_height= "70DP"android:layout_weight= "1" android:gravity= "right" > <textview android:layout_width= "Wrap_co Ntent "android:layout_height=" "20DP" android:text= "2 days Left"/> <textview android:lay
          Out_width= "10DP" android:layout_height= "10DP" android:background= "@drawable/rectangle_radius_fen" android:gravity= "Center" android:text= "Regiment" android:textsize= "5DP" Android:layout_margin

 right= "5DP"/> </LinearLayout> </LinearLayout> </LinearLayout> </ScrollView>

A background image file in the Drawable folder

Rectangle_radius_fen.xml

Description: Very simple, is to set a square with rounded corners

<?xml version= "1.0" encoding= "Utf-8"?> <shape xmlns:android=
"http://schemas.android.com/apk/res/" Android "
  android:shape=" Rectangle >
  <!--define fill gradient color-->
  <solid android:color= "#F97F49"/>
  <!--settings filled-->
  <padding android:left= "1DP"
    android:top= "1DP"
    android:right= "1DP"
    android:bottom= "1DP"/>
  <!--set Rounded rectangle-->
  <corners android:radius= "2DP"/>
</shape >

Background code:

Fragment_hot.java

Description: Here is not much to say, the annotation inside is very clear

Package Com.example.cg.fangduo;
Import Android.content.Context;
Import Android.graphics.Color;
Import Android.os.Bundle;
Import android.support.v4.app.Fragment;
Import Android.util.TypedValue;
Import android.view.Gravity;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import Android.widget.ScrollView;
Import Android.widget.TextView;
 /** * A Simple {@link Fragment} subclass.
  * * Public class Fragment_hot extends fragment {//define the current page private view view;
  Private LinearLayout Line_fragment_hot_main;
  Private ScrollView Id_stickynavlayout_innerscrollview; @Override public View Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestat
    E) {view = Inflater.inflate (R.layout.fragment_hot, container, false);
    Id_stickynavlayout_innerscrollview = (ScrollView) View.findviewbyid (R.id.id_stickynavlayout_innerscrollview); Line_Fragment_hot_main = (linearlayout) View.findviewbyid (R.id.line_fragment_hot_main); for (int i=0;i<10;i++) {/** * Set the outermost linearlayout of each item * * LinearLayout Itemmain = new Linearl
      Ayout (Getactivity ()); Itemmain.setorientation (linearlayout.horizontal); Sets whether the linearlayout is horizontal or vertical linearlayout.layoutparams Itemmainparams = new Linearlayout.layoutparams (ViewGroup.LayoutPa Rams. Match_parent, dip2px (Getactivity (), 80)); Set wide with high Itemmainparams.setmargins (0,dip2px (Getactivity (), 1), 0,0);
      The interval between setting each item and the previous control is 1dip itemmain.setlayoutparams (itemmainparams); Itemmain.setbackgroundcolor (Color.White); Set Background color itemmain.setverticalgravity (gravity.center);
      Set Alignment/** * Set left picture linearlayout * * * linearlayout itempic = new LinearLayout (getactivity ());
      Itempic.setorientation (linearlayout.horizontal);
      Linearlayout.layoutparams itempicparams = new Linearlayout.layoutparams (0, dip2px (getactivity (), 70), 1); ItEmpic.setlayoutparams (Itempicparams);
      Itempic.setverticalgravity (gravity.center_vertical);
      /** * Set Picture * * * ImageView imgpic = new ImageView (getactivity ());
      Imgpic.setimageresource (R.drawable.desktop_device); Linearlayout.layoutparams imgpicparams = new Linearlayout.layoutparams (dip2px (getactivity (),
      ViewGroup.LayoutParams.WRAP_CONTENT), dip2px (Getactivity (), ViewGroup.LayoutParams.WRAP_CONTENT));
      Imgpicparams.leftmargin = dip2px (Getactivity (), 5);  imgpicparams.gravity = Gravity.left;
      Must add this sentence, SetMargins will only work, and this sentence must also under SetMargins imgpic.setlayoutparams (Imgpicparams);
      /** * Picture LinearLayout loading Picture * * Itempic.addview (imgpic, imgpicparams);
      /** * to the main linearlayout load Picture linearlayout * * Itemmain.addview (ITEMPIC);
      /** * Set the middle text display linearlayout * * * linearlayout itemtext = new LinearLayout (getactivity ());
      Itemtext.setorientation (linearlayout.vertical); LinearLayout.layoutparams itemtextparams = new Linearlayout.layoutparams (0, dip2px (getactivity (), 70), 1);
      Itemtext.setlayoutparams (Itemtextparams);
      Itemtext.setverticalgravity (gravity.center_vertical);
      TextView Txtone = new TextView (getactivity ());
      Txtone.settext ("Zhujiang June Jing Qu"); Txtone.settextsize (Typedvalue.complex_unit_dip, 12); Sets the font size and sets its unit to Dip Txtone.getpaint (). Setfakeboldtext (True); Font plus rent linearlayout.layoutparams txtoneparams = new Linearlayout.layoutparams (dip2px (Getactivity (), ViewGroup.Layout
      params.wrap_content), dip2px (Getactivity (), ViewGroup.LayoutParams.WRAP_CONTENT));
      Txtoneparams.weight = 1;
      Txtoneparams.setmargins (0, 0, 0, 0);
      txtoneparams.gravity = Gravity.left;
      Txtone.setlayoutparams (Txtoneparams);
      Itemtext.addview (Txtone);
      TextView txttwo = new TextView (getactivity ());
      Txttwo.settext ("Harbin");
      Txttwo.getpaint (). Setfakeboldtext (True); Txttwo.settextsize (Typedvalue.complex_unit_dip, 8); Linearlayout.layoutparams txttwoparams = new Linearlayout.layoutparams (dip2px (getactivity (),
      ViewGroup.LayoutParams.WRAP_CONTENT), dip2px (Getactivity (), ViewGroup.LayoutParams.WRAP_CONTENT));
      Txttwoparams.weight = 1;
      Txttwo.setlayoutparams (Txttwoparams);
      Itemtext.addview (Txttwo);
      TextView txtthree = new TextView (getactivity ());
      Txtthree.settext ("10,000 to 50,000");
      Txtthree.getpaint (). Setfakeboldtext (True);
      Txtthree.settextsize (Typedvalue.complex_unit_dip, 8);
      Txtthree.setlayoutparams (Txtoneparams);
      Itemtext.addview (Txtthree);
      TextView txtfour = new TextView (getactivity ());
      Txtfour.settext ("8000 Yuan/M");
      Txtfour.settextsize (Typedvalue.complex_unit_dip, 10);
      Txtfour.settextcolor (Color.parsecolor ("#F97F49"));
      Txtfour.getpaint (). Setfakeboldtext (True);
      Txtfour.setlayoutparams (Txtoneparams);
      Itemtext.addview (Txtfour);
      Itemmain.addview (Itemtext); /** * Definition Right Display information frame * * LiNearlayout line_right_text = new LinearLayout (getactivity ());
      Line_right_text.setorientation (linearlayout.horizontal);
      Linearlayout.layoutparams rightparams = new Linearlayout.layoutparams (0, dip2px (getactivity (), 70), 1);
      Line_right_text.setlayoutparams (Rightparams);  Line_right_text.setgravity (Gravity.right);
      Right-aligned TextView daytxt = new TextView (getactivity ()); Linearlayout.layoutparams daytxtparams = new Linearlayout.layoutparams (dip2px (getactivity (),
      ViewGroup.LayoutParams.WRAP_CONTENT), dip2px (Getactivity (), ViewGroup.LayoutParams.WRAP_CONTENT));
      Daytxt.setlayoutparams (Daytxtparams);
      Daytxt.settext ("2 days Left"); Daytxt.settextcolor (Color.parsecolor ("#F97F49")); Set Color Daytxt.settextsize (Typedvalue.complex_unit_dip, 10); Sets the text size Daytxt.getpaint (). Setfakeboldtext (True);
      Set text style, Bold//daytxt.setpadding (0,2,2,0);
      Line_right_text.addview (Daytxt);
      TextView tuantxt = new TextView (getactivity ()); LinearlaYout.
      Layoutparams tuantxtparams = new Linearlayout.layoutparams (dip2px (Getactivity (), a), dip2px (Getactivity (), 12));
      Tuantxtparams.setmargins (dip2px (Getactivity (), 2), dip2px (getactivity (), 0), dip2px (Getactivity (), 5), 0);
      Tuantxt.setlayoutparams (Tuantxtparams);  Tuantxt.setbackgroundresource (R.drawable.rectangle_radius_fen);
      Set TextView background picture tuantxt.setgravity (Gravity.center);
      Tuantxt.settext ("Regiment");
      Txtfour.getpaint (). Setfakeboldtext (True);
      Tuantxt.settextsize (Typedvalue.complex_unit_dip, 8);
      Tuantxt.settextcolor (Color.parsecolor ("#ffffff"));
      Line_right_text.addview (Tuantxt);
      Itemmain.addview (Line_right_text);
    Line_fragment_hot_main.addview (Itemmain);
  } return view; /** * Device pixel (DIP,DP) Turn screen pixel (px) * px is pixel, if you use PX, you will use the actual pixel painting, compared to a bar, drawing a length of 240px horizontal line, in the 480-wide simulator is half the screen width, and in the 320-wide simulator is 2/3 screen width
       Out. * And dip, is the screen of the high divided into 480 points, wide divided into 320 points.
   For example, you make a 160dip horizontal line, whether you are in 320 or 480 of the simulator, is half the length of the screen.
 * @param context * @param dipvalue  * @return */public static int dip2px (context, float Dipvalue) {final float scale = Context.getresource
    S (). Getdisplaymetrics (). density;
  return (int) (Dipvalue * scale + 0.5f);
   /** * Converts PX value to SP value to ensure text size unchanged * * @param pxvalue * @param pxvalue * (Displaymetrics class attribute scaleddensity) * @return */public static int px2sp (context, float Pxvalue) {final float Fontscale = Context.getreso
    Urces (). Getdisplaymetrics (). scaleddensity;
  return (int) (Pxvalue/fontscale + 0.5f);
   /** * Converts SP value to PX value to ensure text size unchanged * * @param spvalue * @param spvalue * (Displaymetrics class attribute scaleddensity) * @return */public static int sp2px (context, float Spvalue) {final float Fontscale = Context.getreso
    Urces (). Getdisplaymetrics (). scaleddensity;
  return (int) (Spvalue * fontscale + 0.5f);

 }
}

Effect Chart:

I hope this article will help you with the Android program.

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.