App boot interface, you can play it like this

Source: Internet
Author: User

App boot interface, you can play it like this

What is ViewPager? We may feel strange when we hear this word, but I believe most of us have seen these interfaces. In fact, it is the effect of the guiding interface that we use for the first time after installing an app. This is done by ViewPager. Today, let's join in the world of ViewPager.

Theoretical Basis In fact, it is a theoretical basis, but it is just a little bit of knowledge, so don't be nervous. ViewPager uses the android. support. v4.view. ViewPager Control During ADT development. We need to know this. We can regard ViewPager as a ListView-style control, and then look at ViewPager from the perspective of ListView, it will be very easy. ListView requires an adapter, as does ViewPager; ListView needs to register Item event listening, as does ViewPager. We will discuss the underlying details later.

After learning about the above, I believe we all have a general understanding. Then we will officially start.

How to Use ViewPager?

First, we need to declare it in the XML file. Note that we reference the android. support. v4.view. ViewPager control, as shown below:

 

Then, use findViewById in the Java code to avoid NullPointerExcetion.
We understand that ViewPager is a View container, so we certainly need to have a View, so we create several views for rendering in the layout folder. Because it is similar, I will write only one XML file here.


  
      
       
            
    
   
          
   

Now everything is ready. Therefore, we need to create an adapter. Note that the adapter must inherit fromPagerAdapterThe specific code is as follows:

Package com. mark. viewpagerdemo; import java. util. list; import android. content. context; import android. support. v4.view. pagerAdapter; import android. support. v4.view. viewPager; import android. view. view;/*** this class is used as an adapter for switching the ViewPager Activity (View, in fact, the principle of ViewPager can be viewed as a ListView. * @ author lhdn **/public class ViewPageAdapter extends PagerAdapter {// list is used to store the view in the container, context is the context private List.
  
   
Views; private Context context; public ViewPageAdapter (List
   
    
MViews, Context mContext) {this. context = mContext; this. views = mViews;}/*** destroy unnecessary views in time */@ Override public void destroyItem (view container, int position, Object object) {(ViewPager) container ). removeView (views. get (position);}/*** the function of this method is similar to the getView function of ListViewAdapter */@ Override public Object instantiateItem (View container, int position) {(ViewPager) container ). addView (views. get (position); return views. get (position) ;}@ Override public int getCount () {// TODO Auto-generated method stub return views. size () ;}@ Override public boolean isViewFromObject (View arg0, Object arg1) {// determine whether the current view is the expected view return (arg0 = arg1 );}}
   
  

Method:

@Override    public Object instantiateItem(View container, int position) {        ((ViewPager) container).addView(views.get(position));        return views.get(position);    }

It is like the getView method of ListViewAdapter. The function is to obtain a view.

If you do not need to add an effect to the image, this is actually done. We can test the effect and find that this small case is feasible.

Add some effects to ViewPager

The so-called add effect is to add a few small dots, such as some small bright points and small dark points that will appear below when we slide the View, the purpose is to show that we did slide the ViewPager, it is also beautiful. So how can we implement it? The answer is to use ImageView, but remember to add it on the page where ViewPager is located without adding other XML files. Then we can set the event in the OnPageChangeListener Processing Event of ViewPager. As follows:


  
              
           
            
             
       
      
     
    
   
  
Package com. mark. viewpagerdemo; import java. util. arrayList; import java. util. list; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. support. v4.view. viewPager; import android. support. v4.view. viewPager. onPageChangeListener; import android. view. layoutInflater; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; public class Guide extends Activity implements OnPageChangeListener {private ViewPager vp; // you must pay attention to an adapter when using viewpager. Therefore, you must create a private ViewPageAdapter vpAdapter object for an adapter; // create some View views for private List placement in our ViewPager container
  
   
Views; // private ImageView [] dots for storing images; // int [] ids = new int [] {R. id. iv1, R. id. iv2, R. id. iv3}; private Button enter; @ Override protected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); setContentView (R. layout. guide); initViews (); initDots ();}/*** initialize the view inside the ViewPager machine */public void initViews () {views = new ArrayList
   
    
(); LayoutInflater inflater = LayoutInflater. from (this); // Add view views to ViewPager. add (inflater. inflate (R. layout. one, null); views. add (inflater. inflate (R. layout. two, null); views. add (inflater. inflate (R. layout. three, null); // apply for resources for the button that enters the main interface. Because the button value is in the third view, this is the Guide, you must obtain the third view before using the findViewById () method enter = (Button) views. get (2 ). findViewById (R. id. start_btn); enter. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub Intent intent = new Intent (Guide. this, MainActivity. class); startActivity (intent); finish () ;}}); // create ViewPager and add the adapter vp = (ViewPager) findViewById (R. id. viewpager); vpAdapter = new ViewPageAdapter (views, this); vp. setAdapter (vpAdapter); // register the listener event vp for ViewPager. setOnPageChangeListener (this);}/*** initialize the resource of the required vertex */public void initDots () {dots = new ImageView [views. size ()]; for (int I = 0; I <dots. length; I ++) {dots [I] = (ImageView) findViewById (ids [I]) ;}} //////////////////////////////////////// //// onViewPagerChangeListener interface method start @ Override public void onPageScrollStateChanged (int arg0) {}@ Override public void onPageScrolled (int arg0, float arg1, int arg2) {}@ Override public void onPageSelected (int arg0) {for (int I = 0; I <ids. length; I ++) {if (arg0 = I) {dots [I]. setImageResource (R. drawable. login_point_selected);} else {dots [I]. setImageResource (R. drawable. login_point );}}} //////////////////////////////////////// //// onViewPagerChangeListener interface method end}
   
  

After the test, we found that! In this way, the functions we need are fully implemented.

In-Depth Thinking

Although we have completed the use of ViewPager, but think about it carefully, are we actually done?
Actually, it is not. In this case, every time we open this APP, a boot interface will appear, which is not in line with the facts, because we don't want to see this guide interface every time, what we need to do now is how to display the guide interface only at the first time.

Implementation idea: Use a variable to store it in the storage of files. Check this value every time you open the APP. If this is the first time you use it, you will jump to the guiding interface. If not, so we need to implement the interface of this intermediate layer. The result is that the interface of the intermediate layer is displayed when the APP is opened, and then jumps to another boot interface or main interface.

The XML Code is as follows:


  
      
   
  
Package com. mark. viewpagerdemo; import android. app. activity; import android. content. intent; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; import android. OS. bundle; import android. OS. handler; public class Welcome extends Activity {// set a delay TIME for the page Jump to obtain the TIME private static final int TIME = 2000; private static final int GO_HOME = 1000; private static final int GO_GUIDE = 1001; // you can set a parameter to display the guide interface only when you enter the page for the first time. This parameter must be stored as a local parameter, // see the following initValue method private boolean isFirstIn = true; private void initValue () {SharedPreferences sp = getSharedPreferences ("ViewPagerDemo", MODE_PRIVATE); isFirstIn = sp. getBoolean ("isFirstIn", true); if (isFirstIn) {mHandler. sendEmptyMessageDelayed (GO_GUIDE, TIME); Editor editor = sp. edit (); editor. putBoolean ("isFirstIn", false); editor. commit ();} else {mHandler. sendEmptyMessageDelayed (GO_HOME, TIME) ;}// the waiting TIME cannot be in the main process. Therefore, use handler private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case GO_HOME: goHome (); break; case GO_GUIDE: goGuide (); break ;};};@ Override protected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); setContentView (R. layout. welcome); initValue ();} private void goHome () {Intent I = new Intent (Welcome. this, MainActivity. class); startActivity (I); finish ();} private void goGuide () {Intent I = new Intent (Welcome. this, Guide. class); startActivity (I); finish ();}}
Welcome. java in-depth analysis:

Because we have set the wait time on the welcome interface, it is best to use handler to update the interface, in line with the "Update UI in the main thread" principle. Therefore, the SharedPreferences is used to implement the worth record.

In fact, I think the initialization method in the initValue method is not particularly good. If it is carried out in static code, the effect will be better.

The use of handler is a crucial knowledge point. We need to remember to update the UI interface in the main thread. Therefore, msg. what is passed to other threads in the main thread should be processed.

Test Results

After clicking "run program", we will find that the guiding interface appears only when the APP is used for the first time. Once we enter the main interface, the guiding interface will not appear again. Unless you reinstall ,(^__^) Hey ......

Knowledge Point Review

The main process of this small project is as follows,
* First, I learned what ViewPager is,
* Then I learned how to use the ViewPagerAdapter,
* Processing the PageChange event
* Learned how to use handler with UI updates
* Then, the constant value is added to implement the "one-time plan"
* The next step is complete. Although the interface is not easy to understand, the core ideas are all here.

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.