Android implementation of local picture sliding Guide Effect Example _android

Source: Internet
Author: User
Tags abs event listener gety object object stub

Today, the reason for the release of this article is a user requirements, is to achieve the local picture sliding guide effect. This effect is generally common on news clients, and its functions are:

1, the top of a single picture left and right drag sliding;

2, with guidance;

3, only slide the top of a single picture, do not slide the page, the following text content does not move;

4, similar to the function of the news client

For all of us to understand better, let's take a look at the effect chart to be implemented:

The above is the realization of the effect of the picture, in fact, the principle is not difficult, we just need to Android-support-v4.jar package Viewpager control set to local can be, but the interface is a little bit of trouble, but after reading this article, we later use the direct call on the line. Also hope this article can be helpful to everyone.

OK, let's start our implementation process, mainly to introduce the implementation steps and some core code. First we need to add Android-support-v4.jar to the project, and then let's look at the program structure:

Let me briefly introduce the principle of implementation:

The layout page is set to local, limits its height, and then generates a layout interface for the sliding picture collection and sets the appropriate data adapter and listener events in the code. Change the corresponding dot picture and display caption in the toggle event Listener, because the interface underneath the slide picture doesn't need to change the content, so it's easy to get the content out of the screen, so you need to set up ScrollView to show the scroll bar when the content is relatively long. I'll show you how to get Viewpager and ScrollView to work together below.

First look at the core code in the layout interface of Android.support.v4.view.ViewPager:

<android.support.v4.view.viewpager
    android:id= "@+id/image_slide_page"
    android:layout_width= "Fill_ Parent "
    android:layout_height=" 180dip "
    android:focusable=" true "/>

In the program structure, Mainactivity.java is the activity that starts, and Topicnews.java is the acitivity that shows the headlines. When displaying, we need to initialize the objects in the Topicnews.java to the following code:

/** * Initialize/private void Initeviews () {//sliding picture Area imagepageviews = new arraylist<view> (); 
    Layoutinflater inflater = Getlayoutinflater ();
    Main = (ViewGroup) inflater.inflate (r.layout.page_topic_news, NULL); 
    
    Viewpager = (Viewpager) Main.findviewbyid (r.id.image_slide_page);
    Dot Picture Area parser = new Newsxmlparser ();
    int length = Parser.getslideimages (). length;
    Imagecircleviews = new Imageview[length];
    Imagecircleview = (viewgroup) Main.findviewbyid (r.id.layout_circle_images);
    Slidelayout = new Slideimagelayout (topicnews.this);
    
    Slidelayout.setcircleimagelayout (length);
      for (int i = 0;i < length;i++) {Imagepageviews.add (Slidelayout.getslideimagelayout (Parser.getslideimages () [i]));
      Imagecircleviews[i] = slidelayout.getcircleimagelayout (i);
    Imagecircleview.addview (Slidelayout.getlinearlayout (Imagecircleviews[i], 10, 10)); //Set the default sliding title Tvslidetitle = (TextView) Main.findviewbyid (R).Id.tvslidetitle);
    
    Tvslidetitle.settext (Parser.getslidetitles () [0]);
    
    Setcontentview (main); 
    Set Viewpager viewpager.setadapter (New Slideimageadapter ());
  Viewpager.setonpagechangelistener (New Imagepagechangelistener ());
 }

The declaration code for the above object looks like this:

The set of sliding pictures
  private arraylist<view> imagepageviews = null;
  Private ViewGroup main = null;
  Private Viewpager Viewpager = null;
  Current Viewpager index
  private int pageIndex = 0; 
  
  View
  private ViewGroup Imagecircleview = null containing the dot picture;
  Private imageview[] imagecircleviews = null; 
  
  Sliding title
  private TextView tvslidetitle = null;
  
  Layout settings class
  private slideimagelayout slidelayout = null;
  Data parsing class
  private newsxmlparser parser = null;

Because the layout file is not set directly in the Topicnews activity that shows the headline, that is, by inflate the layout into the view control, the PAGE_TOPIC_ is used View in News.xml, you need to pass Main.findviewbyid (), as shown in the following code:

Main = (ViewGroup) inflater.inflate (r.layout.page_topic_news, NULL);
Viewpager = (Viewpager) Main.findviewbyid (r.id.image_slide_page);

Instead of being used directly like this:

Viewpager = (Viewpager) Findviewbyid (r.id.image_slide_page);

This is what you need to be aware of when you use it.

The Newsxmlparser class is used to parse the displayed data, because this example is just a demo example, so in this class I just set some fixed data to display, no Dynamic Data set, this is clear, the code is as follows:

Package com.image.indicator.parser;
Import Java.io.InputStream;
Import Java.util.HashMap;

Import java.util.List;

Import Org.xmlpull.v1.XmlPullParser;

Import android.util.Xml;
Import COM.IMAGE.INDICATOR.R;
Import Com.image.indicator.entity.News;

Import com.image.indicator.utility.FileAccess;

 /** * Resolution of the News data list * @Description: To parse the list of news data, here is an example, specifically no longer implemented.

 * @File: Newsxmlparser.java * @Package com.image.indicator.parser * @Author Hanyonglu * @Date 2012-6-18 02:31:26 * @Version V1.0 */public class Newsxmlparser {//News list Private list 

About Newsxmlparser This class, the implementation is relatively simple, no longer detailed, interested friends can be set in the development process of dynamic data and parsing.

When I talked about the implementation principle above, I mentioned the need to set the layout interface of the sliding picture collection, so how do I set the layout? We need to use slideimagelayout here.

The Slideimagelayout class is the class used to generate the layout of the slide picture area and the layout of the dot picture. I use the For loop to set the layout of the slide picture and the dot picture in the above code (that is, the initialization method Initeviews () in Topicnews.java). Several methods of Getslideimagelayout (), Getcircleimagelayout () and getlinearlayout () are used in the loop. Below look at its function, look at the next getslideimagelayout () implementation code:

/**
   * Generate sliding picture area layout
   * @param index
   * @return
  /public View getslideimagelayout (int index) {
    // LinearLayout linearlayout containing textview
    imagelinerlayout = new LinearLayout (activity);
    Linearlayout.layoutparams imagelinerlayoutparames = new Linearlayout.layoutparams (
        LinearLayout.LayoutParams.WRAP_CONTENT, 
        LinearLayout.LayoutParams.WRAP_CONTENT,
        1);
    
    ImageView IV = new ImageView (activity);
    Iv.setbackgroundresource (index);
    Iv.setonclicklistener (New Imageonclicklistener ());
    Imagelinerlayout.addview (iv,imagelinerlayoutparames);
    Imagelist.add (iv);
    
    return imagelinerlayout;
  }

Because the slide picture generally needs to set its link or the corresponding ID, in order to click on the corresponding activity, display the appropriate content or details. Here I do not have too many settings, just click on the display title and link address, the code is as follows:

Slide page Click event Listener
  Private class Imageonclicklistener implements onclicklistener{
    @Override public
    Void OnClick (View v) {
      //TODO auto-generated method stub
      toast.maketext (Activity, parser.getslidetitles () [ PageIndex], Toast.length_short). Show ();
      Toast.maketext (activity, Parser.getslideurls () [PageIndex], Toast.length_short). Show ();
  

The Getcircleimagelayout () method is mainly to generate the corresponding ImageView object for the dot picture, the code is as follows:

/**
   * Generate dot Image Area Layout object
   * @param index
   * @return
   /public
  imageview getcircleimagelayout (int index) {
    ImageView = new ImageView (activity); 
    Imageview.setlayoutparams (New Layoutparams (10,10));
    Imageview.setscaletype (SCALETYPE.FIT_XY);
    
    Imageviews[index] = ImageView;
     
    if (index = = 0) { 
      ////default selected First picture
      Imageviews[index].setbackgroundresource (r.drawable.dot_selected); 
    } else { 
      imageviews[index].setbackgroundresource (r.drawable.dot_none); 
    } 
     
    return imageviews[index];
  }

The Getlinearlayout () method adds the appropriate linearlayout layout for the dot picture to set the distance between the dot pictures, as follows:

/** *
   Get linearlayout
   * @param view
   * @param width
   * @param height
   * @return
  /public view Getlinearlayout (View view,int width,int height) {
    linearlayout linerlayout = new LinearLayout (activity);
    Linearlayout.layoutparams linerlayoutparames = new Linearlayout.layoutparams (
        width, 
        height,
        1);
    Here it is also best to customize settings and be interested in setting yourself up.
    linerlayout.setpadding (0, 0);
    Linerlayout.addview (view, linerlayoutparames);
    
    return linerlayout;
  }

The Getcircleimagelayout () and Getlinearlayout () methods combine the code in the structure of the For loop in Newstopic.java as follows:

Imagecircleviews[i] = slidelayout.getcircleimagelayout (i);
Imagecircleview.addview (Slidelayout.getlinearlayout (Imagecircleviews[i], 10, 10));

These two methods can be used in conjunction with the graceful realization of the layout of its dot image.

The above is an introduction to the two classes on Newsxmlparser and Slideimagelayout, let's go back to the Topicnews class to continue with the relevant knowledge. After the object initialization (Initeviews () method) in Topicnews, you also need to set the data adapters and listener events in the Viewpager object. The code for the data adapter in Viewpager is as follows:

Slide picture data Adapter Private class Slideimageadapter extends Pageradapter {@Override public int getcount () { 
    return Imagepageviews.size (); 
    @Override public boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = Arg1; @Override public int GetItemPosition (Object object) {//TODO auto-generated method stub retur 
    n Super.getitemposition (object); @Override public void Destroyitem (View arg0, int arg1, Object arg2) {//TODO auto-generated method s 
    Tub ((Viewpager) arg0). Removeview (Imagepageviews.get (arg1)); 
      @Override public Object Instantiateitem (View arg0, int arg1) {//TODO auto-generated method stub
      
      ((Viewpager) arg0). AddView (Imagepageviews.get (arg1)); 
    Return Imagepageviews.get (ARG1);  @Override public void Restorestate (parcelable arg0, ClassLoader arg1) {//TODO auto-generated method 
 
  stub}  @Override public parcelable SaveState () {//TODO auto-generated a stub return null; @Override public void Startupdate (View arg0) {//TODO auto-generated method stub} @Ov
 Erride public void Finishupdate (View arg0) {//TODO auto-generated method stub}}

The Viewpager event listener code is as follows:

Sliding page Change Event listener
  Private class Imagepagechangelistener implements Onpagechangelistener {
    @Override 
    public void onpagescrollstatechanged (int arg0) { 
      //TODO auto-generated method stub 
 
    } 
 
    @Override public 
    Void onpagescrolled (int arg0, float arg1, int arg2) { 
      //TODO auto-generated method stub 
 
    } 
 
    @Override 
    public void onpageselected (int index) { 
      pageIndex = index;
      Slidelayout.setpageindex (index);
      Tvslidetitle.settext (Parser.getslidetitles () [index]);
      
      for (int i = 0; i < imagecircleviews.length i++) { 
        Imagecircleviews[index].setbackgroundresource ( r.drawable.dot_selected);
        
        if (index!= i) { 
          imagecircleviews[i].setbackgroundresource (r.drawable.dot_none); 
        } 
      }
    } 
  }

The event listener mainly transforms the caption and the dot picture in the callback function onpageselected (int index).

Because the content underneath the sliding area is invariant, which is not sliding, as I mentioned above, the content may go beyond the scope of the screen, so we need to use ScrollView to display the scroll bar when there is too much content. Some friends might think, to show the scroll bar I also know how to use ScrollView. What I want to say here is that there are viewpager controls, there are ScrollView, and if two view is used alone there will be no problem. Unfortunately, however, there are problems with the use of two. What's the problem? Is the phenomenon of bounce when sliding pictures, it is difficult to slip when sliding, I feel very hard when sliding, and the picture is sliding not past, this is the conflict between the two view, because two view is sliding view, will calculate the corresponding position and the corresponding distance.

How can we solve this conflict? Here we need to rewrite the ScrollView onintercepttouchevent () callback function. You need to add a new Scrollviewextend class to your program and inherit from ScrollView, and here's the code:

Package Com.image.indicator.control;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;

Import Android.widget.ScrollView; /** * can be compatible with Viewpager ScrollView * @Description: resolves viewpager sliding bounce problem in ScrollView * @File: Scrollviewextend.java * @Pac Kage Com.image.indicator.control * @Author Hanyonglu * @Date 2012-6-18 pm 01:34:50 * @Version V1.0/public class S

  Crollviewextend extends ScrollView {//sliding distance and coordinates private float xdistance, ydistance, XLAST, Ylast;
  Public Scrollviewextend (context, AttributeSet attrs) {Super (context, attrs); @Override public boolean onintercepttouchevent (motionevent ev) {switch (ev.getaction ()) {case Motioneve Nt.
        Action_down:xdistance = Ydistance = 0f;
        XLAST = Ev.getx ();
        Ylast = Ev.gety ();
      Break
        Case MotionEvent.ACTION_MOVE:final Float CurX = Ev.getx ();
        
        Final float Cury = ev.gety (); Xdistance + MAth.abs (Curx-xlast);
        Ydistance + + math.abs (cury-ylast);
        XLAST = CurX;
        
        Ylast = Cury;
        if (Xdistance > Ydistance) {return false;
  } return super.onintercepttouchevent (EV);

 }
}

Then add this extended view in our layout code, as follows:

<com.image.indicator.control.scrollviewextend
    android:layout_width= "match_parent"
    android:layout_ height= "Fill_parent" > ...

</com.image.indicator.control.ScrollViewExtend>

The above actions will resolve the conflict between Viewpager and ScrollView, so you can use the scroll bar to display the contents unchanged. Here's another explanation, because this example is just a demo example, so underneath the sliding picture, I'm just using a picture to fix the headline activity underneath. Of course, there is a need for friends, you can transform it, the sliding image of the lower area to add a ListView, such as view and so on to display the corresponding request information.

Some friends may notice that there is a transparent effect underneath the sliding picture area, as shown in the following illustration:

This implementation is not difficult, just add the background attribute to the appropriate layout code, as follows:

Android:background= "#55000000"

Of course, the transparency of the setting has a scope, interested friends to search the Internet, no longer detailed here.

This example, in addition to implementing the Android local picture sliding guide effect, also implements the above navigation menu switch effect, regarding this effect is not unusual, because some people on the net have already implemented this function. But here, I do not quite like them, click on the top of the news classification when the sensitivity is better, that is, the probability of the point is relatively large. Because the top of the news classification text is relatively small, it is sometimes not easy to think of points. The following is a brief introduction to the implementation process and the corresponding code.

Because the background picture needs to be animated when you click on the news category, I added a class: Imageanimatioin, which handles the animation effect when the picture moves. Its

The code is as follows:

/**
   * Set image Move animation effect
   * @param v
   * @param startx *
   @param toX
   * @param starty *
   @param toY
  * * public static void Setimageslide (View v, int startx, int toX, int starty, int toY) {
    translateanimation anim = new Tra Nslateanimation (StartX, ToX, Starty, ToY);
    Anim.setduration (m);
    Anim.setfillafter (true);
    V.startanimation (ANIM);
  }

Here's a look at the code in the event listener when clicking on a news category, because in this process you need to calculate the position of the moving picture and toggle the following body content, as follows:

 News classification Event Listener private class Itemonclicklistener implements onclicklistener{@Override public void OnClick (View
      
      V) {//TODO auto-generated method Stub itemwidth = Findviewbyid (r.id.layout). GetWidth (); Switch (V.getid ()) {case R.id.tv_title_news:imageanimatioin.setimageslide (Tvselecteditem, startx, 0, 0, 0)
        ;
        startx = 0;
        
        Tvselecteditem.settext (R.string.title_news_category_tops);
        Display headline information Intent.setclass (Mainactivity.this, Topicnews.class);
        Vnewsmain = Getlocalactivitymanager (). StartActivity ("Topicnews", Intent). Getdecorview ();
      Break
        Case R.id.tv_title_info:imageanimatioin.setimageslide (Tvselecteditem, StartX, itemwidth, 0, 0);
        StartX = Itemwidth;
        
        Tvselecteditem.settext (R.string.title_news_category_info);
        Display Information Intent.setclass (mainactivity.this, Infonews.class); Vnewsmain = Getlocalactivitymanager ().StartActivity ("Infonews", Intent). Getdecorview ();
      Break
        Case R.id.tv_title_blog:imageanimatioin.setimageslide (Tvselecteditem, StartX, Itemwidth * 2, 0, 0);
        STARTX = Itemwidth * 2;
        
        Tvselecteditem.settext (R.string.title_news_category_blog);
        Display blog Information intent.setclass (mainactivity.this, Blognews.class);
        Vnewsmain = Getlocalactivitymanager (). StartActivity ("Blognews", Intent). Getdecorview ();
      Break
        Case R.id.tv_title_magazine:imageanimatioin.setimageslide (Tvselecteditem, StartX, Itemwidth * 3, 0, 0);
        STARTX = Itemwidth * 3;
        
        Tvselecteditem.settext (R.string.title_news_category_magazine);
        Display magazine Information Intent.setclass (Mainactivity.this, Magazinenews.class);
        Vnewsmain = Getlocalactivitymanager (). StartActivity ("Magazinenews", Intent). Getdecorview ();
      Break Case R.id.tv_title_domain:imageanimatioin.
        Setimageslide (Tvselecteditem, StartX, Itemwidth * 4, 0, 0);
        STARTX = Itemwidth * 4;
        Tvselecteditem.settext (R.string.title_news_category_domain);
        Display industry Information Intent.setclass (Mainactivity.this, Domainnews.class);
        Vnewsmain = Getlocalactivitymanager (). StartActivity ("Domainnews", Intent). Getdecorview ();
      Break
        Case R.id.tv_title_more:imageanimatioin.setimageslide (Tvselecteditem, StartX, Itemwidth * 5, 0, 0);
        STARTX = Itemwidth * 5;
        
        Tvselecteditem.settext (R.string.title_news_category_more);
        Show more information Intent.setclass (Mainactivity.this, Morenews.class);
        Vnewsmain = Getlocalactivitymanager (). StartActivity ("Morenews", Intent). Getdecorview ();
      Break
      Default:break;
      //Replace the news subject in Layout rlnewsmain.removeallviews ();
    Rlnewsmain.addview (Vnewsmain, params);
 }
  }

This is set to change the layout of a news category in a main frame, rather than directly, so you need to be aware of it. Also, when you click on a category of news other than the headline, it's just a picture, and there's a need for a friend to transform it, no more.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.