New Ui-java code dynamically adding controls or XML layouts

Source: Internet
Author: User

New Ui-java code dynamically adding controls or XML layouts

--Reprint Please indicate source: Coder-pig, welcome reprint, do not use for commercial use!


Piglet Android Development Exchange Group has been established, welcome everyone to join, both novice, rookie, Big God can, piglet a person's

Strength is limited after all, the writing out of things will certainly have a lot of flaws, welcome to point out, brainstorm, let the pig's blog

More detailed, help more people, O (∩_∩) o Thank you!

Piglet Android Development Exchange Group: Piglet Android Development Exchange Group Group number: 421858269

new Android UI Instance Daquan directory: http://blog.csdn.net/coder_pig/article/details/42145907



Introduction to this section:

In the previous section, we learned the pure Java code to load the layout, there is a bit of dynamic layout of the foundation, in this section

What we're explaining is that, on the basis of loading XML, you can add the view control dynamically! and dynamically load the XML

Layout!



The text of this section:


1.Java Code Add control dynamically:

There are two types of dynamically added components, the difference is whether the first Setcontentview (R.layout.activity_main) is required;

The following demo dynamically adds a button to the interface

The layout of the Activity_main.xml file is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/relativelayout1 "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    android:orientation= "vertical"    tools:context= " Com.jay.example.trendsinflateviewdemo.MainActivity ">    <textview         android:id=" @+id/txttitle "        Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "I am the layout of the XML file load"/ >    </RelativeLayout>

The first type: no need for Setcontentview ();

Package Com.jay.example.trendsinflateviewdemo;import Android.app.activity;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.viewgroup.layoutparams;import Android.widget.Button;import Android.widget.relativelayout;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Button Btnone = New button (this); Btnone.settext ("I am a dynamically added button"); Relativelayout.layoutparams LP2 = new Relativelayout.layoutparams (                  layoutparams.wrap_content, LayoutParams.WRAP _content);          Lp2.addrule (relativelayout.center_in_parent);  Layoutinflater Inflater = Layoutinflater.from (this); Relativelayout rly = (relativelayout) inflater.inflate (R.layout.activity_main, null). Findviewbyid ( R.ID.RELATIVELAYOUT1); Rly.addview (BTNONE,LP2); Setcontentview (rly);}}

The second kind: Need setcontentview ();

Package Com.jay.example.trendsinflateviewdemo;import Android.app.activity;import Android.os.bundle;import Android.view.viewgroup.layoutparams;import Android.widget.button;import Android.widget.relativelayout;public Class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); Button Btnone = New button (this); Btnone.settext ("I am a dynamically added button"); Relativelayout.layoutparams LP2 = new Relativelayout.layoutparams (                  layoutparams.wrap_content, LayoutParams.WRAP _content);          Lp2.addrule (relativelayout.center_in_parent);          Relativelayout rly = (relativelayout) Findviewbyid (R.ID.RELATIVELAYOUT1); Rly.addview (BTNONE,LP2); SetContentView ( rly);}}



Analysis Summary:

The code is simple, after creating the button, we create a Layoutparams object to set the button size, and

The AddRule () method sets the position of the button!

The first method: loads the Activity_main layout with the layoutinflate inflate () method , obtains the outer container, and then

AddView Add the button into the container, the last Setcontentview ();

The second method: because we have loaded the layout through the Setcontetview () method, we can now pass the Findviewbyid

find this outer container , then AddView, and finally Setcontentview ()!

In addition, the view node that he set for this setcontentview () is the root node of the entire XML!



It's not hard to add controls about this dynamically, if you read the previous article < plain java loading layout >,



2.Java Code dynamically loading XML layouts


Next, let's change one, this time loading an XML file! Add XML files dynamically!

Write down the layout file first:

Activity_main.xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:id=" @+id/relativelayout1 "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    android:orientation= "vertical"    tools:context= " Com.jay.example.trendsinflateviewdemo.MainActivity ">    <button         android:id=" @+id/btnload "        Android:layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "dynamically load Layout"/>    </RelativeLayout>

dynamically loaded XML file Inflate.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:gravity= "Center"    android:orientation= "vertical"    android:id= "@+id/ly_inflate" >    <textview        android: Layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:text= "I am the layout of Java code loading"/>    <button        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content        " Android:text= "I'm a little button in the layout"/></linearlayout>

and then we got to the Mainactivity.java:

Package Com.jay.example.trendsinflateviewdemo;import Android.app.activity;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup.layoutparams;import Android.widget.button;import Android.widget.linearlayout;import Android.widget.relativelayout;public class Mainactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main);//  Get Layoutinflater object; final Layoutinflater inflater = Layoutinflater.from (this); Get External Container object final relativelayout rly = (relativelayout) Findviewbyid (R.ID.RELATIVELAYOUT1); Button BtnLoad = (button) Findviewbyid (r.id.btnload); Btnload.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {//loads the layout object to be added linearlayout ly = (linearlayout) inflater.inflate (r.layout.inflate_ly , NULL, FALSE). Findviewbyid (r.id.ly_inflate);//Set the size and position of the load layout Relativelayout.layoutparamS LP = new Relativelayout.layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);  Lp.addrule (relativelayout.center_in_parent); Rly.addview (LY,LP);}});}}

Run:



The next step is to analyze the code:

① Gets the container object:

Final Relativelayout rly = (relativelayout) Findviewbyid (R.ID.RELATIVELAYOUT1);

② gets the Inflater object, loading the XML of the added layout, and finding the outermost root node through Findviewbyid

Final layoutinflater inflater = Layoutinflater.from (this);

LinearLayout ly = (linearlayout) inflater.inflate (
R.layout.inflate_ly, NULL, FALSE). Findviewbyid (
R.id.ly_inflate);

③ set the size and location information for this container:

Relativelayout.layoutparams LP = new Relativelayout.layoutparams (
Layoutparams.wrap_content, layoutparams.wrap_content);
Lp.addrule (relativelayout.center_in_parent);

④ added to the outer container:

Rly.addview (LY,LP);





Well, about the content of dynamically adding controls or XML through Java code!

Also, be reminded that after AddView (), when this view is not needed, the use can be Removeview ()

This view is removed Oh!





New Ui-java Code dynamically adds a control or XML 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.