"New Project & Use Viewpager" to implement an Android ebook reader app

Source: Internet
Author: User

At the end of this chapter has been released application demo, has implemented all the text and subsequent articles described in all the functions, we can first download down to play, welcome to comment below this article, the small side is very need to encourage support!!!

The ultimate effect of novel reader see the previous post on a blog post

Create a new project

We are about to embark on an Android development journey, starting with a new project.

After you choose to start a new project, a window opens to let you set the app's name (beginning with capital letters), and a URL-like thing to distinguish between different developers, if you have your own domain name can be set directly like me (propaganda a wave of the small side of their own site ~http:// xfangfang.cn), or set a favorite address.

Then the default interface is selected, where we choose the blank activity is good.

By clicking Next, we have created a running Android program and we will see the following interface.

Simple Introduction to Android programming

On the left is your reading application of the project directory, different folders are stored in different files, has been a rough description, if there is anything unclear, we also ask the search engine.

Here is a closer look at the contents of the Mainactivity file.

1 public class Mainactivity extends Appcompatactivity {2 3     @Override4     protected void OnCreate (Bundle Savedinstancestate) {5         super.oncreate (savedinstancestate); 6         Setcontentview (R.layout.activity_main); 7     }8}

Activity is one of the four components of Android, and it's easy to understand that each interface of the program we run corresponds to an activity, so activities are the main battlefield where we write code, and when an activity starts running, it calls our rewritten function oncreat, in this function Setcontentview (r.layout.activity_main); The layout file is set up to provide a display interface for our activities.

The layout file is saved under the Layout folder with. xml as the suffix, so let's take a closer look.

Android uses an XML file as a layout file, a closed parenthesis represents a component, and some components can be used as containers for other components, such as relativelayout in, can be put TextView, the use of this "container" to better write the Android interface, for different resolutions, Android devices with different screen ratios.

In addition to using the code-writing interface, Android Studio provides another way to set the layout.

In this interface, we only need to use the mouse through the simple drag to complete the interface design, but unfortunately, the method of dragging is not omnipotent, the program does not fully understand the human idea, the use of drag components and directly write XML files combined to better complete the work. Similarly, here do not add to the introduction of Android development Knowledge, Xiao Fang This tutorial blog is not expected to occupy too much space in the basic part, just introduce the relevant concepts, beginners can be based on different keywords to search the Internet.

Start running

Here, we can try to run the current code, you can use the real machine to connect the data cable to the computer for debugging, you can also use the Android virtual machine.

The small side uses the genymotion virtual machine to run the program, clicks the small green arrow in the toolbar above, selects the good device to be able to run the program in the device.

Now, as a beginner you can try to run your new Android app and try to change the TextView text.

Using Viewpager

Let's take a look at the final implementation of our Viewpager.

First step to modify the layout

Viewpager this thing, in the view of the small side is to put a number of activities together, you can easily slip to slip, so that we need a number of different layout files, corresponding to each page in the Viewpager, right-click the Layout folder, tap New, select the first layout Resource file will be able to create a layout files, the default layout file contains the LinearLayout, we can put a textview as a mark.

, two new files were created.

Here, we start by modifying the main interface layout and inserting Viewpager into the layout.

Activity_main.xml

1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "3     xmlns:tools=" Http://schemas.android.com/tools "4     android:id=" @+id/activity_main "5     Android:layout_width= "Match_parent" 6     android:layout_height= "match_parent" 7     android:paddingbottom= "@ Dimen/activity_vertical_margin "8     android:paddingleft=" @dimen/activity_horizontal_margin "9     android: paddingright= "@dimen/activity_horizontal_margin"     android:paddingtop= "@dimen/activity_vertical_margin" 11     tools:context= "cn.xfangfang.reader.MainActivity" >12     <android.support.v4.view.viewpager         android:id= "@+id/container"          Android:layout_width= "Match_parent"         android:layout_height= "match_parent"/>-</ Relativelayout>

To this end, the layout file's setup is finished, and the mainactivity is now modified.

Step two Create Fragment

Previously, there are a lot of interfaces on Viewpager, where every interface is a fragment,fragment that can be understood as something like activity, and we need to build our own fragment class for each interface to inherit from fragment.

1      Public Static classFindbooksfragmentextendsFragment {2 3          Publicfindbooksfragment () {4         }5 6 @Override7          PublicView Oncreateview (Finallayoutinflater inflater, ViewGroup container,8 Bundle savedinstancestate) {9 TenView Rootview = Inflater.inflate (R.layout.pager_book_find, Container,false); One  A             returnRootview; -         } -  the     } -  -      Public Static classReadlistfragmentextendsFragment { -  +          Publicreadlistfragment () { -         } +  A @Override at          PublicView Oncreateview (Finallayoutinflater inflater, ViewGroup container, - Bundle savedinstancestate) { -  -View Rootview = Inflater.inflate (r.layout.pager_book_list, Container,false); -  -             returnRootview; in         } -  to}

Note that in the code block above the bold two lines, we need to write the name of the newly created two layout file to the bold specified location, when the fragment is created, will automatically call the Oncreatview function, here temporarily do not write other functions.

With two fragment created, we also need to set up an adapter for Viewpager.

Step three Create the Viewpager adapter

1      Public classSectionspageradapterextendsFragmentpageradapter {2         PrivateArraylist<fragment>datas;3 4          PublicSectionspageradapter (fragmentmanager FM) {5             Super(FM);6         }7 8          Public voidSetData (arraylist<fragment>datas) {9              This. datas =datas;Ten         } One  A @Override -          PublicFragment GetItem (intposition) { -             returnDatas = =NULL?NULL: Datas.get (position); the         } -  - @Override -          Public intGetCount () { +             returnDatas = =NULL? 0: Datas.size (); -         } +  A}

Here the adapter plays the role of passing the fragment to Viewpager, and by rewriting the GetItem function, we pass the datas in Sectionspageradapter to Viewpager.

Final integration

Here's a look at the oncreat function of mainactivity.

1     PrivateSectionspageradapter Msectionspageradapter;2     PrivateViewpager Mviewpager;3 4 @Override5     protected voidonCreate (Bundle savedinstancestate) {6         Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_main);8 9Msectionspageradapter =NewSectionspageradapter (Getsupportfragmentmanager ());Tenarraylist<fragment> datas =NewArraylist<>(); OneDatas.add (Newreadlistfragment ()); ADatas.add (Newfindbooksfragment ()); - Msectionspageradapter.setdata (datas); -  theMviewpager =(Viewpager) Findviewbyid (r.id.container); - Mviewpager.setadapter (msectionspageradapter); -}

Declare the Viewpager and its adapters in mainactivity.

9-13 lines initialize the adapter and add two fragment to the adapter's datas array.

15 lines believe that we all understand, do not understand the students can search for learning.

Finally, set the adapter for Viewpager.

In just a few steps, we completed a viewpager of the whole process, let our program run up ~

See if we have a prototype of our reading application, and we enclose all the code of mainactivity.

Mainactivity

 Public classMainactivityextendsappcompatactivity {PrivateSectionspageradapter Msectionspageradapter; PrivateViewpager Mviewpager; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Msectionspageradapter=NewSectionspageradapter (Getsupportfragmentmanager ()); ArrayList<Fragment> datas =NewArraylist<>(); Datas.add (Newreadlistfragment ()); Datas.add (Newfindbooksfragment ());        Msectionspageradapter.setdata (datas); Mviewpager=(Viewpager) Findviewbyid (R.id.container);    Mviewpager.setadapter (Msectionspageradapter); }     Public Static classFindbooksfragmentextendsFragment { Publicfindbooksfragment () {} @Override PublicView Oncreateview (Finallayoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview= Inflater.inflate (R.layout.pager_book_find, container,false); returnRootview; }    }     Public Static classReadlistfragmentextendsFragment { Publicreadlistfragment () {} @Override PublicView Oncreateview (Finallayoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View Rootview= Inflater.inflate (r.layout.pager_book_list, container,false); returnRootview; }    }     Public classSectionspageradapterextendsFragmentpageradapter {PrivateArraylist<fragment>datas;  PublicSectionspageradapter (fragmentmanager FM) {Super(FM); }         Public voidSetData (arraylist<fragment>datas) {             This. datas =datas; } @Override PublicFragment GetItem (intposition) {            returnDatas = =NULL?NULL: Datas.get (position); } @Override Public intGetCount () {returnDatas = =NULL? 0: Datas.size (); }    }}

Complete the primary use of Viewpager, you can now feel free to practice some of your own, add different components to the two pages and experience the fun of Android development.

Finally think about it or attach the final implementation of our application, that is, the previous article that the app.

Https://pan.baidu.com/s/1eR7AOEY

Not to be continued ... The next article describes the use of Recyclerview implementation of the classification interface to write, please look forward!!!

"New Project & Use Viewpager" to implement an Android ebook reader app

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.