Android: Fragments of Demo

Source: Internet
Author: User

Now that you have mastered the important points of knowledge about fragmentation, there may be some deficiencies in the use of flexibility, so it's time to get into the best practice of our chapter.

As mentioned earlier, fragments are often used in tablet development, mainly to solve the problem that the screen space is not fully utilized. Does that mean that the programs we develop need to provide a mobile version and a Pad version? Indeed, many companies do, but it will waste a lot of manpower and resources. Because it costs a lot to maintain two versions of code, each time you add something new, you need to write it down in two code, and each time you find a bug, you need to change it in two parts of the code. So our best practice today is to teach you how to write apps that are compatible with both mobile and tablet.

Remember a news app that was mentioned at the beginning of this chapter? Now we will use the knowledge learned in this chapter to write a simple version of the news app, and require it to be compatible with both mobile phones and tablets. Create a new good one Fragmentbestpractice project and get started!

The first step is to prepare a news entity class, new Class news, as shown in the following code:

public class News {private string title; private string content;

Public String GetTitle () {

return title;

}

public void Settitle (String title) {

This.title = title;

}

Public String getcontent () {

return content;

}

public void SetContent (String content) {

this.content = content;

}

}

The code of the News class is relatively simple, the title field represents the news title, and the Content field represents the news contents. Then create a new News_item.xml layout that is used as the layout for the sub-items in the News list:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

<textview android:id= "@+id/news_title" android:layout_width= "match_parent" android:layout_height= "wrap_content "Android:singleline=" true "android:ellipsize=" End "android:textsize=" 18SP "android:paddingleft=" 10DP "Android: paddingright= "10DP" android:paddingtop= "15DP" android:paddingbottom= "15DP"

/>

</LinearLayout>

This code is also very simple, just put a TextView to display the news in the LinearLayout

Problem. Looking closely at TextView, you will find that there are several properties that we have not learned before. Android:padding means adding padding around the control so that the text does not close to the edge. Android:singleline set to True means that the TextView can only be displayed in a single line. The android:ellipsize is used to set the thumbnail of the text when the text content exceeds the width of the control, which is specified here as end to indicate the thumbnail at the tail.

Next you need to create an adapter for the news list, let the adapter inherit from Arrayadapter, and specify the generic as the news class. To create a new class Newsadapter, the code looks like this:

public class Newsadapter extends Arrayadapter<news> {

private int resourceId;

Public Newsadapter (Context context,int Textviewresourceid, list<news>

Objects) {

Super (context, Textviewresourceid, objects);

ResourceId = Textviewresourceid;

}

@Override

Public View GetView (int position, View Convertview, ViewGroup parent) {News news= getItem (position);

View view;

if (Convertview = = null) {

View = Layoutinflater.from (GetContext ()). Inflate (resourceId, NULL);

} else {

view = Convertview;

}

TextView Newstitletext = (TextView) View.findviewbyid (r.id.news_title);

Newstitletext.settext (News.gettitle ());

return view;

}

}

As you can see, in the GetView () method, we get the news class at the appropriate location and let the headlines in the headlines appear in the list.

So basically the code for the News list section is written, so let's look at how to write the code for the News content section. Create a new layout file News_content_frag.xml, as shown in the following code:

<relativelayout xmlns:android= " htt p://schemas.android.com/apk/res/android "android:layout_width=" match_parent "android:layout_height=" match_parent ">

<linearlayoutandroid:id= "@+id/visibility_layout" android:layout_width= "Match_parent" android:layout_height= " Match_parent "android:orientation=" vertical "android:visibility=" invisible ">

<textviewandroid:id= "@+id/news_title" android:layout_width= "match_parent" android:layout_height= "wrap_content "android:gravity=" center "android:padding=" 10DP "android:textsize=" 20sp "/>

<imageviewandroid:layout_width= "Match_parent" android:layout_height= "1DP" android:scaletype= "FitXY" Android: src= "@drawable/spilt_line"/>

<textviewandroid:id= "@+id/news_content" android:layout_width= "match_parent" android:layout_height= "0DP" android:layout_weight= "1" android:padding= "15DP" android:textsize= "18sp"/>

</LinearLayout>

<imageviewandroid:layout_width= "1DP" android:layout_height= "Match_parent" android:layout_alignparentleft= " True "android:scaletype=" Fitxy "android:src=" @drawable/spilt_line_vertical "/>

</RelativeLayout>

The layout of the news content can be divided into two parts, the head shows the complete news headlines, the body part shows the news

Content, separated by a thin line in the middle. The thin line here is achieved by using ImageView to display a very narrow picture, setting ImageView's Android:scaletype property to Fitxy, which means that the image fills the size of the entire control.

Then create a new Newscontentfragment class that inherits from Fragment, as shown in the following code:

public class Newscontentfragment extends Fragment {

Private view view;

@Override

Public View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {

View = Inflater.inflate (R.layout.news_content_frag, container, false);

return view;

}

public void Refresh (string newstitle, String newscontent) {

View visibilitylayout = View.findviewbyid (r.id.visibility_layout);

Visibilitylayout.setvisibility (view.visible);

TextView Newstitletext = (TextView) View.findviewbyid (r.id.news_title); TextView Newscontenttext = (TextView) View.findviewbyid (R.id.news_

content);

Newstitletext.settext (newstitle);// Refresh the title of the News

Newscontenttext.settext (newscontent);// Refresh the content of the news

}

}

The Oncreateview () method was first loaded with the News_content_frag layout we just created, which is nothing to explain. The next step is to provide a refresh () method, which is used to display the title and content of the news on the interface. As you can see, the Findviewbyid () method is used to obtain the title and content control of the news, respectively, and then set the parameters passed in by the method.

Next, create a news content layout that is used in the activity, creating a new news_content.xml, as shown in the following code:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

<fragmentandroid:id= "@+id/news_content_fragment" Android:name= " Com.example.fragmentbestpractice.NewsContentFragment "android:layout_width=" Match_parent "android:layout_height= "Match_parent"

/>

</LinearLayout>

Here we give full play to the reusability of the code, directly in the layout of the introduction of the Newscontentfragment, which is equivalent to the News_content_frag layout of the content automatically added in.

Then create a new newscontentactivity as the activity that displays the news content, as shown in the following code:

public class Newscontentactivity extends Activity {

public static Voidactionstart (context context, string Newstitle, String newscontent) {

Intent Intent = new Intent (context,newscontentactivity.class); Intent.putextra ("News_title", Newstitle); Intent.putextra ("News_content", newscontent);

Context.startactivity (Intent);

}

@Override

protected void OnCreate (bundlesavedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title); Setcontentview (r.layout.news_content);

String newstitle =getintent (). Getstringextra ("News_title");

// get incoming news headlines

String newscontent = Getintent (). Getstringextra ("News_content");

// get incoming news content

Newscontentfragment newscontentfragment = (newscontentfragment)

Getfragmentmanager ()

. Findfragmentbyid (R.id.news_content_fragment);

Newscontentfragment.refresh (Newstitle, newscontent);

// refresh newscontentfragment interface

}

}

As you can see, in the OnCreate () method we get the incoming news headlines and news content through Intent,

Then call Fragmentmanager's Findfragmentbyid () method to get the instance of Newscontentfragment, then call its refresh () method, and the title and content of the news in, you can display the data. Note Here we also provide a ACTIONStart () method, remember its role? If you forget, read it again 2.6.3 knots.

The next step is to create a layout to display the news list, creating a new News_title_frag.xml with the code as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

<listviewandroid:id= "@+id/news_title_list_view" android:layout_width= "Match_parent" android:layout_height= " Match_parent ">

</ListView>

</LinearLayout>

The code for this layout is very simple, with only one ListView in it. But presumably you have guessed that this layout is not for activities, but for fragmentation, so we also need to create a fragment to load the layout. Create a new Newstitlefragment class that inherits from Fragment, as shown in the following code:

public class Newstitlefragmentextends Fragment implements

Onitemclicklistener {

Private ListView Newstitlelistview;

Private list<news> newslist; Privatenewsadapter adapter; Private Boolean Istwopane;

@Override

Public Voidonattach (activity activity) {

Super.onattach (activity);

newslist = Getnews ();// Initialization of news data

adapter = new Newsadapter (activity, R.layout.news_item, newslist);

}

@Override

Public View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {

View view = Inflater.inflate (R.layout.news_title_frag, container, false);

Newstitlelistview = (ListView) View.findviewbyid (r.id.news_title_

List_view); Newstitlelistview.setadapter (adapter); Newstitlelistview.setonitemclicklistener (this);

return view;

}

@Override

public void onactivitycreated (Bundle savedinstancestate) {

Super.onactivitycreated (savedinstancestate);

if (Getactivity (). Findviewbyid (r.id.news_content_layout)! = null) {

Istwopane = true;// news_content_layout layout can be found when the two-page mode

} else {

Istwopane = false;// news_content_layout layout is not found for single-page mode

}

}

@Override

Public Voidonitemclick (adapterview<?> parent, viewview, int position, long ID) {

News news = Newslist.get (position);

if (Istwopane) {

// If it is in two-page mode, refresh the contents of newscontentfragment

Newscontentfragment newscontentfragment= (newscontentfragment)

Getfragmentmanager (). Findfragmentbyid (R.id.news_

Content_fragment);

Newscontentfragment.refresh (News.gettitle (), news.getcontent ());

} else {

// If it is a single-page mode, start newscontentactivity directly

Newscontentactivity.actionstart (Getactivity (), News.gettitle (), news.getcontent ());

}

}

Private List<news>getnews () {

list<news> newslist = newarraylist<news> (); News news1 = new News ();

News1.settitle ("Succeed in College as a learning Disabled Student"); News1.setcontent ("College freshmen would soon learn to Live with aroommate, adjust to a new social Sceneand survive less-than-stellar dining Hallfood. Students withlearning Disabilities Willface These transitions whilealso grappling with a few more hurdles. "); Newslist.add (NEWS1);

News news2 = new News ();

News2.settitle ("Google Android execpoached by the China ' s Xiaomi"); News2.setcontent ("China's Xiaomihas poached a key googleexecutive involved in Thetech giant ' s androidphones, in a move see Nas a coup for the rapidly growing Chinese smartphone maker. "); Newslist.add (NEWS2);

return newslist;

}

}

The code for this class is a bit long, I'll focus on explaining it. Depending on the life cycle of the fragment, we know that the Onattach () method executes first, so here are some data initialization operations, such as calling the Getnews () method to get a few simulated news data, and completing the creation of the Newsadapter. The News_title_frag layout is then loaded in the Oncreateview () method and a click event is registered to the ListView of the news list. Next in the Onactivitycreated () method, we can determine whether the current is a two-page mode or a single-page mode by finding a View with the ID news_content_layout, which is the News_content_layout View appears only in two-page mode, which you will see later in the layout. Then in the ListView Click event we can judge, if the current is a single page mode, start a new activity to display the news content, if the current is a double page mode, update the data in the news content fragment.

The rest of the work is very simple, modify the code in the Activity_main.xml as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" >

<fragmentandroid:id= "@+id/news_title_fragment" Android:name= " Com.example.fragmentbestpractice.NewsTitleFragment "

Android:layout_width= "Match_parent" android:layout_height= "Match_parent"

/>

</LinearLayout>

The code above indicates that in single-page mode, only one piece of news title will be loaded. Then create a new LAYOUT-SW600DP

folder and create a new Activity_main.xml file under this folder, the code looks like this:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" >

<fragmentandroid:id= "@+id/news_title_fragment" Android:name= " Com.example.fragmentbestpractice.NewsTitleFragment "android:layout_width=" 0DP "

android:layout_height= "Match_parent" android:layout_weight= "1"/>

<framelayoutandroid:id= "@+id/news_content_layout" android:layout_width= "0DP" android:layout_height= "Match_ Parent "android:layout_weight=" 3 ">

<fragmentandroid:id= "@+id/news_content_fragment" Android:name= "Com.example.fragmentbestpractice.

Newscontentfragment "android:layout_width=" match_parent "android:layout_height=" Match_parent "/>

</FrameLayout>

</LinearLayout>

As you can see, in two-page mode we have introduced two fragments and placed the fragments of news content under a framelayout layout, and the ID of this layout is news_content_layout. Therefore, the ability to find this ID is a two-page mode, otherwise it is a single-sided mode.

Finally, the mainactivity slightly modified, the title bar to remove, the code is as follows:

public class Mainactivity extends Activity {

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title);

Setcontentview (R.layout.activity_main);

}

}

So that all of our writing work has been completed, and run it quickly! First run on the phone simulator, as shown in effect 4.15.

Figure 4.15

You can see the title of the two news, and the text that goes beyond the screen section is replaced with an ellipsis at the tail. Then click on the second news, will launch a new activity to display the content of the news, effect 4.16 shows.

Figure 4.16

Next, run the program on the Tablet emulator, and click on the second piece of news, as shown in effect 4.17.

Figure 4.17

Android: Fragments of demo

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.