Use code dynamic Layout in Android

Source: Internet
Author: User

Use code dynamic Layout in Android


This article describes the use of code dynamic layout in Android, sometimes depending on the needs, such as the number of items on the server to determine the app page layout control (display number, icon, etc.). The dynamic layout through Java code is described here.


One,:


You can find the pictures.


second, give the XML file layout

<?xml version= "1.0" encoding= "Utf-8"? ><scrollview xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @android: Co         Lor/white "> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_content "            android:orientation= "Vertical" > <!--here the title bar can be customized because each page has a title, return, etc.--<relativelayout Android:id= "@+id/layout_titlebar" android:layout_width= "Match_parent" Android:layout_heigh t= "48DP" android:layout_marginbottom= "20DP" android:background= "#ed4255" > <textvie W android:id= "@+id/text_title" style= "@style/text.title" android:layout_width                = "Match_parent" android:layout_height= "match_parent" android:gravity= "center" Android:text= "Business function Introduction"/> &Lt;/relativelayout> <!--Sub-layouts are dynamically generated by code-<linearlayout android:id= "@+id/layout_more" Android:layout_width= "Match_parent" android:layout_height= "Match_parent" Android:orientati on= "vertical" android:padding= "4DP"/> </LinearLayout></ScrollView>


iii. Child Entry XML layout file

<framelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "84DP" android:layout_weight= "1.0" android:clickable= "true" > <imageview Andro Id:id= "@+id/image_icon" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android        Oid:layout_gravity= "Center_horizontal" android:layout_margintop= "16DP" android:duplicateparentstate= "true" android:src= "@drawable/ic_department_01_normal"/> <textview android:id= "@+id/text_title" and Roid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Center_horizon        Tal|bottom "android:background=" @null "android:layout_marginbottom=" 6DP "android:gravity=" center " Android:duplicateparentstate= "true" android:textcolor= "@drawable/text_service_color" android:textsize= "1 4DP "/></framelayout> 




iv. Dynamic layout of Java code

/** * @author Gao_chun * */public class Mainactivity extends Activity implements onclicklistener{private ViewGroup MMo  Relayout;    The Parent layout container (the dynamically loaded resource picture and the layout of the text will be added inside it)/* (non-javadoc) * @see app.ui.titleactivity#oncreate (android.os.Bundle) */        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);   Initui ();        Guarantee the uniqueness of the Startup method} private void Initui () {Setcontentview (r.layout.activity_main); Locate the container (the control here is LinearLayout, converted to ViewGroup because ViewGroup is the base class for the container) Mmorelayout = (viewgroup) Findviewbyid (r.id.layout_more        ); Because the text is also dynamically generated, use an array file in Android to define the resource file and remove the final string[] categories = Getresources (). Getstringarray (R.array.categori        ES);     final int size = Categories.length;          String[] The length of final int rowCount = SIZE/3; Number of rows required for layout (three per line)/** * Dynamic Add Layout Method Package * Parameter 1. Parent Container 2. Resource literal array 3. Starting from the first 4. Number of lines */Fillview S (mmorelayout, categories, 0, RowCount); } private void Fillviews (ViewGroup layout, string[] categories, int start, int end) {//table first line VIEW.INFL        Ate (this, r.layout.layout_line_horizonal, layout);            for (int i = start; i < end; i++) {//Find index, easy to add picture file according to index and text final int firstindex = i * 3;            final int secondindex = i * 3 + 1;            final int thirdindex = i * 3 + 2;            Final String firstcategory = Categories[firstindex];            Final String secondcategory = Categories[secondindex];            Final String thirdcategory = Categories[thirdindex]; The control is to load the local image, through the application package to find a rule-named Picture resource File//---> because there are two effects, one is the default picture, and the second is to press the trigger after the picture and text final int firstdrawabl Enormal = Getresources (). Getidentifier (String.Format ("Ic_department_%02d_normal", FirstIndex + 1), "Draw            Able ", Getapplicationcontext (). Getpackagename ()); Final int seconddrawablenormal = Getresources (). Getidentifier (String.Format ("Ic_department_%02d_normal ", Secondindex + 1)," drawable ", Getapplicationcontext (). Getpackagename ());                    Final int thirddrawablenormal = Getresources (). Getidentifier (String.Format ("Ic_department_%02d_normal",            Thirdindex + 1), "drawable", Getapplicationcontext (). Getpackagename ());                    Final int firstdrawablepressed = Getresources (). Getidentifier (String.Format ("ic_department_%02d_pressed",            FirstIndex + 1), "drawable", Getapplicationcontext (). Getpackagename ());                    Final int seconddrawablepressed = Getresources (). Getidentifier (String.Format ("ic_department_%02d_pressed",            Secondindex + 1), "drawable", Getapplicationcontext (). Getpackagename ());                    Final int thirddrawablepressed = Getresources (). Getidentifier (String.Format ("ic_department_%02d_pressed",            Thirdindex + 1), "drawable", Getapplicationcontext (). Getpackagename ());      This is where the default picture found above and the picture pressed are placed in the statelistdrawable cache      Final statelistdrawable firstdrawable = new statelistdrawable (); Firstdrawable.addstate (New int[]{android.            R.attr.state_pressed}, Getresources (). getdrawable (firstdrawablepressed));            Firstdrawable.addstate (New int[]{}, Getresources (). getdrawable (Firstdrawablenormal));            Final statelistdrawable seconddrawable = new statelistdrawable (); Seconddrawable.addstate (New int[]{android.            R.attr.state_pressed}, Getresources (). getdrawable (seconddrawablepressed));            Seconddrawable.addstate (New int[]{}, Getresources (). getdrawable (Seconddrawablenormal));            Final statelistdrawable thirddrawable = new statelistdrawable (); Thirddrawable.addstate (New int[]{android.            R.attr.state_pressed}, Getresources (). getdrawable (thirddrawablepressed));            Thirddrawable.addstate (New int[]{}, Getresources (). getdrawable (Thirddrawablenormal));            Parent Layout Final LinearLayout linearlayout = new LinearLayout (this); FirstSub-layout view.inflate (this, r.layout.layout_line_vertical, linearlayout);            View.inflate (This, r.layout.layout_department, linearlayout);            View.inflate (This, r.layout.layout_line_vertical, linearlayout);            Second sub-layout view.inflate (this, r.layout.layout_department, linearlayout);            View.inflate (This, r.layout.layout_line_vertical, linearlayout);            The third sub-layout view.inflate (this, r.layout.layout_department, linearlayout);            View.inflate (This, r.layout.layout_line_vertical, linearlayout);            Layoutparams layoutparams = new Linearlayout.layoutparams (layoutparams.match_parent,layoutparams.wrap_content);            Layout.addview (LinearLayout, layoutparams);            The last line of the table view.inflate (this, r.layout.layout_line_horizonal, layout);            According to the index Getchildat to the specified location final View Firstview = Linearlayout.getchildat (1);        Firstview.settag (firstcategory); Set the tag to make it easy to postTo determine which firstview.setonclicklistener to click (this);            Set Click final TextView Firsttextview = (TextView) Firstview.findviewbyid (r.id.text_title);   Firsttextview.settext (firstcategory);            Set Text final ImageView Firstimageview = (ImageView) Firstview.findviewbyid (R.id.image_icon); Firstimageview.setimagedrawable (firstdrawable);            Set the previously cached picture to final View Secondview = Linearlayout.getchildat (3);            Secondview.settag (secondcategory);            Secondview.setonclicklistener (this);            Final TextView Secondtextview = (TextView) Secondview.findviewbyid (r.id.text_title);            Secondtextview.settext (secondcategory);            Final ImageView Secondimageview = (ImageView) Secondview.findviewbyid (R.id.image_icon);            Secondimageview.setimagedrawable (seconddrawable);            Final View Thirdview = Linearlayout.getchildat (5);            Thirdview.settag (thirdcategory); Thirdview.setonclicklistener(this);            Final TextView Thirdtextview = (TextView) Thirdview.findviewbyid (r.id.text_title);            Thirdtextview.settext (thirdcategory);            Final ImageView Thirdimageview = (ImageView) Thirdview.findviewbyid (R.id.image_icon);        Thirdimageview.setimagedrawable (thirddrawable); } */* (non-javadoc) * @see App.ui.titleactivity#onclick (android.view.View) */@Override public void O      Nclick (View v) {Final Object tag = V.gettag ();            Before Settag find the click Position if (tag! = null) {String Department = (string) tag;        Toast.maketext (this, department, 0). Show (); }//Else ignored}}

The tag set during the OnClick event to find out which specific layout the user clicked on

Note: about getresources (). Getidentifier method can be consulted:http://blog.csdn.net/gao_chun/article/details/45891383



Welcome to Download Source:http://download.csdn.net/download/gao_chun/8740979



Use code dynamic Layout in Android

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.