Android Study Notes image carousel...

Source: Internet
Author: User

Android Study Notes image carousel...
Learning Content: 1. android uses ViewPager and PagerAdapter to implement image carousel... 2. use the reflection mechanism to obtain Android resource information... image carousel is a very common animation effect, which is also very commonly used in apps. Here we will simply implement this function. In Android, we want to implement image carousel, you need to use the ViewPager control to implement it. The main function of this control is to achieve the sliding effect of the image... so with the sliding, the film attached on the basis of the sliding achieves the image carousel effect... this control is similar to ListView. You need to use the adapter. The adapter is used to set some effects for carousel... pagerAdapter adapter needs to be used here... the following is an example. The effect of this example is to display the information of the first image while the image is being played... and the following points will change accordingly... first, let's look at the layout file code... this layout file is actually a bit... <android. support. v4.view. viewPager android: id = "@ + id/vp" android: layout_height = "fill_parent" android: layout_width = "fill_parent"/> This sentence must be introduced... otherwise, an error occurs... this means that I set a sliding effect, which fills the entire FrameLayout... each View represents a control, which is displayed in another xml file... below are two xml files...

<?xml version="1.0" encoding="utf-8"?><shape    xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval">    <solid        android:color="#000000">    </solid>    <corners         android:radius="5dip"/></shape>

 

<?xml version="1.0" encoding="utf-8"?><shape    xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="oval">    <solid         android:color="#00ffff"/>    <corners         android:radius="5dip"/></shape>

 

You can configure the xml file to display the View in the preceding way, because the shapes, sizes, and even display modes of these five points are basically the same, if you try to find 5 images or a single image, you can use the Drawable resource to display the image... by loading 5 times... this is obviously unnecessary and will waste unnecessary resources .. therefore, we can use the custom image provided by xml to complete this process... xml provides the shape attribute, custom control .. here I define a solid circle... this solid circle is used to complete the sliding of the image, and the point changes accordingly... it seems that it is not something hard to understand...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <FrameLayout         android:layout_height="300dip"        android:layout_width="fill_parent">        <android.support.v4.view.ViewPager            android:id="@+id/vp"            android:layout_height="fill_parent"            android:layout_width="fill_parent"/>        <LinearLayout             android:layout_height="30dip"            android:layout_width="fill_parent"            android:gravity="center"            android:layout_gravity="bottom"            android:orientation="vertical"            android:background="#20000000"            >            <TextView                 android:id="@+id/tv"                android:layout_height="wrap_content"                android:layout_width="wrap_content"                android:textColor="@android:color/white"                android:text="@string/hello_world"                android:layout_gravity="center_horizontal"                android:layout_marginTop="3dip"/>            <LinearLayout                 android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:orientation="horizontal"                android:layout_marginTop="3dip">                <View                     android:id="@+id/dot_0"                    android:layout_width="5dip"                    android:layout_height="5dip"                    android:layout_marginRight="3dip"                    android:layout_marginLeft="3dip"                    android:background="@drawable/dot"/>                <View                     android:id="@+id/dot_1"                    android:layout_height="5dip"                    android:layout_width="5dip"                    android:layout_marginRight="3dip"                    android:layout_marginLeft="3dip"                    android:background="@drawable/dot_1"/>                  <View                     android:id="@+id/dot_2"                    android:layout_height="5dip"                    android:layout_width="5dip"                    android:layout_marginRight="3dip"                    android:layout_marginLeft="3dip"                    android:background="@drawable/dot_1"/>                  <View                     android:id="@+id/dot_3"                    android:layout_height="5dip"                    android:layout_width="5dip"                    android:layout_marginRight="3dip"                    android:layout_marginLeft="3dip"                    android:background="@drawable/dot_1"/>                  <View                     android:id="@+id/dot_4"                    android:layout_height="5dip"                    android:layout_width="5dip"                    android:layout_marginRight="3dip"                    android:layout_marginLeft="3dip"                    android:background="@drawable/dot_1"/>            </LinearLayout>        </LinearLayout>    </FrameLayout></RelativeLayout>

 

The important part is how to implement this process... the implementation of this process is further explained in the code below...
Package com. example. picture_change; import java. lang. reflect. field; import java. util. arrayList; import java. util. hashMap; import java. util. map. entry; import java. util. map; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. annotation. suppressLint; import android. app. activity; import android. support. v4.view. pagerAdapter; import android. support. v4.view. viewPager; import android. support. v4.view. viewPager. onPageChangeListener; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. view. viewGroup; import android. widget. imageView; import android. widget. textView; import android. widget. toast;/** keys stored in HashMap cannot be repeated... but the value can be repeated... * **/public class MainActivity extends Activity {ArrayList <ImageView> imageSource = null; // stores the image control... arrayList <View> dots = null; // stores 5 points... int [] images = null; // resources for storing images... string [] titles = null; // The title changes as the image changes... textView TV = null; // TextView to display title changes... viewPager viewpager; // ViewPager to achieve the sliding effect... myPagerAdapter adapter; // adapter... map <String, Object> map = new HashMap <String, Object> (); @ SuppressLint ("UseSparseArrays") Map <Integer, Object> mapValues = new HashMap <Integer, object> (); private int curr = 0; private int old = 0; int o = 0; int mapsize; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Toast. makeText (MainActivity. this, "a", Toast. LENGTH_LONG ). show ();/* use reflection to obtain Drawable resources... * Here I have obtained the resource data of 5 images. .this 5 images are separated by a.jpg B .jpg c.jpg d.jpg e.jpg * Here a length <= 1 is used to obtain the data... in fact, this method is not good. It was developed by myself... * No better method... I will introduce the purpose of using reflection here... **/Field [] field = R. drawable. class. getFields (); for (Field f: field) {if (f. getName (). length () <= 1) {try {o ++; String str = "image" + "_" + o; map. put (str, f. getInt (R. drawable. class); // use map To Save image data resources in the form of key-value pairs ...} catch (IllegalArgumentException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} mapsize = map. size ()-1;/* Here I use a map again to save only the Value of the previous map in the form of a key-Value pair... * The purpose of doing so is described below... * **/for (Entry <String, Object> entry: map. entrySet () {mapValues. put (mapsize, entry. getValue (); mapsize --;} init ();} public void init () {// initialization of data information... images = new int [] {R. drawable. a, R. drawable. b, R. drawable. c, R. drawable. d, R. drawable. e}; titles = new String [] {"this is the one picture", "this is two picture", "this is three picture", "this is four picture ", "this is five picture"}; imageSource = new ArrayList <ImageView> (); // initialize imageSource here... for (int I = 0; I <images. length; I ++) {ImageView iamgeview = new ImageView (this); iamgeview. setBackgroundResource (images [I]); imageSource. add (iamgeview);} // a method is used here... we do not need to use findViewById () once ()... the following method effectively solves the reference of multiple findViewById () functions... dots = new ArrayList <View> (); for (int j = 0; j <5; j ++) {String dotid = "dot" + "_" + j; int resId = getResources (). getIdentifier (dotid, "id", "com. example. picture_change "); dots. add (findViewById (resId);} TV = (TextView) findViewById (R. id. TV); TV. setText (titles [0]); viewpager = (ViewPager) findViewById (R. id. vp); adapter = new MyPagerAdapter (); // an adapter object is defined here... viewpager. setAdapter (adapter); // transfer object, bind adapter... viewpager. setOnPageChangeListener (new onpagelistener (); // set a listening effect when the image slides... scheduledExecutorService scheduled = Executors. newSingleThreadScheduledExecutor (); // here we open a thread... scheduled. scheduleAtFixedRate (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub curr = (curr + 1) % images. length; handler. sendEmptyMessage (0); // send the information to Handler, so that the Handler can process the data and complete some operations ...}}, 2, 2, TimeUnit. SECONDS); // sets the internal playback time ...} private class MyPagerAdapter extends PagerAdapter {@ Override public int getCount () {// TODO Auto-generated method stub return images. length ;}@ Override public boolean isViewFromObject (View arg0, Object arg1) {// TODO Auto-generated method stub // determine whether the two pictures are the same... return arg0 = arg1;} @ Override public void destroyItem (ViewGroup container, int position, Object object) {// destroy... release memory... container. removeView (imageSource. get (position) ;}@ Override public Object instantiateItem (ViewGroup container, int position) {/* This method indicates moving to the position of the first image... data transmission is completed by passing a ViewGroup... * We used a Map to save the Value of the previous Map. The real purpose is here .. the purpose is to * obtain the resource information of the currently displayed image .. to put it bluntly, you just need to get (R. drawable. attribute). Why? * What operations should we perform when the displayed image is clicked... **/ImageView v = imageSource. get (position); // get the current image... // position is the value from 0-4... so we can get the value in Map... v. setClickable (true); // set the image to be clickable... final int values = (Integer) mapValues. get (position); // here we get the value of Values saved in map... system. out. println (values); // The following is the listener that triggers the image... v. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// TODO Auto-generated method stub switch (values) {case R. drawable. a: Toast. makeText (MainActivity. this, "a", Toast. LENGTH_LONG ). show (); break; case R. drawable. b: Toast. makeText (MainActivity. this, "B", Toast. LENGTH_LONG ). show (); break; case R. drawable. c: Toast. makeText (MainActivity. this, "c", Toast. LENGTH_LONG ). show (); break; case R. drawable. d: Toast. makeText (MainActivity. this, "d", Toast. LENGTH_LONG ). show (); break; case R. drawable. e: Toast. makeText (MainActivity. this, "e", Toast. LENGTH_LONG ). show (); break ;}}); container. addView (imageSource. get (position); // load all images to the container... return imageSource. get (position) ;}/// define an internal class to listen to images when they change... class onpagelistener implements OnPageChangeListener {@ Override public void evaluate (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 arg0) {// TODO Auto-generated method stub // when a slide occurs, some operations to complete... TV. setText (titles [arg0]); dots. get (arg0 ). setBackgroundResource (R. drawable. dot); dots. get (old ). setBackgroundResource (R. drawable. dot_1); old = arg0; curr = arg0 ;}@suppresslint ("HandlerLeak") private Handler handler = new Handler () {public void handleMessage (Message msg) {// After receiving the message, update the page viewpager. setCurrentItem (curr) ;};}; @ Override public boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

 

Here I use the reflection mechanism to obtain Drawable image resources, and then use the switch method to complete the operations that need to be done when the image is clicked... this is a method I have come up... because Android does not provide methods such as ImageClickListener (), we can only write the image by ourselves... as for the better method, I have not found it... it is also true that there are limits on the ability. This method also took a whole afternoon to come out... note: As a reminder, the HashMap key cannot be retained... however, the value can save duplicate data. If duplicate keys are saved, only the first data will be saved in map, and subsequent data will not be saved... this is also a big note. I planted it here for a long time. Although it is a very low-level error, it is very likely that I will make it without looking at it... therefore, we can remind ourselves here... I will not make such a mistake again next time ..

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.