Android Growth Path (5)--Create a dynamic UI with fragment

Source: Internet
Author: User

The following are simple:

Now use the fragment to implement a simple dynamic UI, click the title of the left title bar, and then the left body bar to display the corresponding article

1. Add two fragment in the Activity_main.xml layout.
One corresponding to the left of the title bar, a corresponding to the right of the body bar

<?xml version= "1.0" encoding= "Utf-8"?><linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:id="@+id/layout_main"android:layout_width="Match_parent"android: Layout_height="Match_parent"android:orientation="Horizontal">                    <fragment  android:layout _width  = "0DP"  android:layout_height  =< Span class= "Hljs-value" > "match_parent"  android:layout_weight  = "1"  class  = " Com.example.fragment.HeadlinesFragment "/>     <fragmentandroid:layout_width="0DP"android:layout_height="Match _parent "android:layout_weight=" 2 "android:id=" @+id/articles_fragment " class="com.example.fragment.ArticleFragment"/>                                        </linearlayout>

2. Then, you need to create a class to place the content. The content is the title on the left and the body on the right.

 Public classIpsum {StaticString[] Headlines = {"Article One","article ."};StaticString[] articles = {"article One\n\nexcepteur pour-over occaecat squid biodiesel umami gastropub, nulla laborum Salvia dreamcatcher Fanny Pack. Ullamco culpa Retro EA, trust Fund excepteur Eiusmod Direct trade Banksy nisi Lo-fi Cray Messenger bag. Nesciunt esse Carles Selvage put a bird on it gluten-free, Wes Anderson ut Trust fund twee occupy viral. Laboris small Batch scenester pork belly, leggings ut farm-to-table aliquip yr nostrud iphone viral next level. Craft Beer Dreamcatcher Pinterest Truffaut Ethnic, authentic brunch. Esse Single-origin Coffee Banksy do next level Tempor. Velit synth Dreamcatcher, Magna Shoreditch in American Apparel messenger bag narwhal PBR ennui farm-to-table. ","article two\n\nvinyl Williamsburg non velit, Master cleanse four Loko banh mi. enim kogi keytar Trust Fund pop-up por Tland gentrify. Non EA typewriter dolore deserunt Austin. Ad Magna Ethical Kogi mixtape Next level. Aliqua pork belly Thundercats, UT pop-up tattooed dreamcatcher Kogi Accusamus photo booth irony Portland. Semiotics Brunch ut locavore irure, enim Etsy laborum Stumptown Carles gentrify post-ironic Cray. Butcher 3 Wolf Moon blog synth, vegan Carles Odd Future. "};}

Before creating the fragment class, take a look at the life cycle of the fragment.
As you can see, in fragment, there are also OnCreate (), OnStart () These methods
The life cycle of fragment can be clearly known by graphs

Fragment is life cycle and activity life cycle.
Fragment is embedded in activity, and its life cycle is directly influenced by the main activity life cycle.
For example, when activity is in the paused state, all of its fragment are in pasued state.

3, first to create a Articlefragment class, inherit fragment. This fragment is part of the right body column.

publicclass ArticleFragment extends Fragment {    publiconCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {                    return inflater.inflate(R.layout.article_view,container,false);        }}

Fragmentation is often used as part of an active user interface and helps to improve the flexibility of the layout.
To draw the layout of the fragment by implementing the Oncreateview () callback method, you must return a view value.
This layout can be defined in an XML file, invoking an Layoutinflater object provided by Oncreateview (), passing in the ID of the layout.

The Oncreateview () method passed three parameters.
Look at the official explanation:
The container parameter passed to Oncreateview () are the parent viewgroup (from the activity's layout) in which yo ur fragment layout'll be inserted.
The savedinstancestate parameter is a Bundle this provides data about the previous instance of the fragment, if T He fragment is being resumed (restoring state is discussed more in the sections about handling the fragment Lifecycle).

The inflate () method also has three parameters:

The resource ID of the layout you want to inflate.

The ViewGroup to is the parent of the inflated layout. Passing the container is important on order for the system to apply layout parameters to the root view of the inflated lay Out, specified by the parent view in which it ' s going.

A Boolean indicating whether the inflated layout should be attached to the ViewGroup (the second parameter) during Inflati On. Because the system is already inserting the inflated layout into the container-passing true W Ould Create a redundant view group in the final layout.)

You can see that Savedinstancestat is a bundle, and if fragmen back to resumed state (which involves the life cycle of fragment), it is used to store the data that the previous fragment instance put in. Therefore, you can save the position of the currently selected article by overloading Onsaveinstancestate.

The articlefragment also requires an Update method to display the article based on the location of the title click.

Add code in Articlefragment:

 Public  class articlefragment extends Fragment {    Final StaticString arg_position ="Articlefragementposition";intMcurrentposition =-1;//Set the current position to-1, which is not selected    @Nullable    @Override     PublicViewOncreateview(Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {if(Savedinstancestate! =NULL) {mcurrentposition = Savedinstancestate.getint (arg_position); }returnInflater.inflate (R.layout.article_view,container,false); }@Override     Public void OnStart() {Super. OnStart ();//In OnStart, check to see if the parameters are passed and ensure that the method is called safeBundle args = Getarguments ();if(Args! =NULL) Updatearticleview (Args.getint (arg_position)); }Else if(Mcurrentposition! =-1) {Updatearticleview (mcurrentposition); }    } Public void Updatearticleview(intPosition) {TextView Article = (TextView) getactivity (). Findviewbyid (r.id.article);        Article.settext (Ipsum.articles[position]);    Mcurrentposition = position; }@Override     Public void onsaveinstancestate(Bundle outstate) {Super. Onsaveinstancestate (Outstate);//Save the current locationOutstate.putint (Arg_position, mcurrentposition); }}

Define the Body bar layout:

<?xml version= "1.0" encoding= "Utf-8"?>    <linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"  Android:orientation="vertical" android:layout_width="Match_parent"android: Layout_height="Match_parent">                        <ScrollViewandroid:layout_width="Match_parent"android:layout_height ="Wrap_content">                                    <TextViewandroid:layout_width="Match_parent"android:layout_height ="Match_parent"android:id="@+id/article"android:padding="16DP "android:textsize=" 18sp ">                                                                                            </TextView>        </ScrollView></linearlayout>

Then create a Headlinesfragment class that inherits the Listfragment. This fragment is the title section on the left.

publicclass HeadlinesFragment extends ListFragment {}

If fragment inherits Listfragment, it already implements the Oncreateview () method by default and returns a ListView, so there is no need to implement the Oncreateview () method.

Sometimes, you need to fragment the data in the activity. Here's a good way to define an interface in fragment that implements this interface in the main activity. When activity receives data through this interface, it is possible to share the data with other fragment when needed.

For example, the title bar of this section of the fragment click on the title A, this time will get the title a position, we need to according to this location to display the corresponding article. Add this interface to the headlinesfragment.

publicclass HeadlinesFragment extends ListFragment {publicinterface OnHeadlinesSelectedListner {        publicvoidonArticleSelected(int position);    }...}

Next, add the title in the title bar. Here fragment inherits the Listfragment, need the adapter (Adapter) to add the content of the title, and in the click to have the corresponding, can get the location of the click. The position here starts at 0, one-to-one ..., but first make sure the activity implements the above interface and calls Onattach ().

 Public  class headlinesfragment extends listfragment {Onheadlinesselectedlistner Mcallback; Public  interface onheadlinesselectedlistner {             Public void onarticleselected(intposition); }@Override     Public void Onattach(Activity activity) {Super. Onattach (activity);//Ensure activity implements interface        Try{mcallback = (onheadlinesselectedlistner) activity; }Catch(ClassCastException e) {Throw NewClassCastException (activity.tostring () +"must implement Onheadlinesselectedlistner"); }    }@Override     Public void onCreate(@Nullable Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Select the List_item style according to the device        intLayout = Build.VERSION.SDK_INT >= build.version_codes.                Honeycomb? Android. R.layout.simple_list_item_activated_1:android. R.layout.simple_list_item_1;//Create an array adapter to the headlines array in the Ipsum classSetlistadapter (NewArrayadapter<string> (Getactivity (), layout, ipsum.headlines)); }@Override      Public void Onlistitemclick(ListView L, View V,intPositionLongID) {Super. Onlistitemclick (L, V, position, id);//Call the interface method so that when implemented in the main activity, the incoming position can be shared,mcallback.onarticleselected (position);//Set Item is selectedGetlistview (). setitemchecked (Position,true); }@Override     Public void OnStart() {Super. OnStart ();//Set to Radio mode       if(Getfragmentmanager (). Findfragmentbyid (r.id.articles_fragment)! =NULL) {Getlistview (). Setchoicemode (Listview.choice_mode_single); }    } }

Finally, the interface is implemented in the main activity

 Public  class mainactivity extends fragmentactivity  implements  Headlinesfragment. Onheadlinesselectedlistner {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); }@Override     Public void onarticleselected(intPosition) {//Here Pass the parameter position, that is Headlinesfragment click on the selected locationArticlefragment Articlefrag = (articlefragment) Getsupportfragmentmanager (). Findfragmentbyid (R.id.articles_        fragment);    Articlefrag.updatearticleview (position); }}

So far, all the code has been written. Run successfully, just like the example picture.

Instead of directly adding fragment directly to the activity's layout, you can actually use a fragmentlayout as a fragment container, and then, when the activity runs, Add or remove by transaction.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/fragment_container"    android:layout_width="match_parent"    android:layout_height="match_parent" />
...if (findViewById(R.id.fragment_container) != null) {            if (savedInstanceState != null) {                return;            }            HeadlinesFragment firstFragment = new HeadlinesFragment();            firstFragment.setArguments(getIntent().getExtras());            getSupportFragmentManager().beginTransaction()                    .add(R.id.fragment_container, firstFragment).commit();        }...

In activity, call Getsupportfragmentmanager () to get the fragmentmanagers. Then call BeginTransaction () to create a fragmenttransaction and add () a fragment.

Multiple fragment can be manipulated by the same fragmenttransaction. When the fragment operation has been completed, such as adding or removing, the final call to commit ().

...ArticleFragment newFragment = new ArticleFragment();Bundle args = new Bundle();args.putInt(ArticleFragment.ARG_POSITION, position);newFragment.setArguments(FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();transaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);transaction.commit();...

Backstack is a stack that activity uses task to manage.
by calling Addtobackstack (), the replacement transaction is saved in the return stack. So the user can press the back key to see the previous fragment.

Android Growth Path (5)--Create a dynamic UI with fragment

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.