Tuesday, September 18, 2012

Android ViewPager Tutorial

Android ViewPager Tutorial - Hallo sahabat Google Android Developer Tutorial, Pada Artikel yang anda baca kali ini dengan judul Android ViewPager Tutorial, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel Android Viewpager tutorial, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Android ViewPager Tutorial
link : Android ViewPager Tutorial

Baca juga


Android ViewPager Tutorial



ANDROID VIEWPAGER TUTORIAL   


ViewPager helps screen slide transitions between one entire screen to another(swipe left or right).This type of UI pattern is common with  setup wizards or slideshows.Currently, one of the most popular Widgets in the Android library is the ViewPager.  It's implemented in several of the most-used Android apps, like the Google Play app.
Figure 1 Shows the demonstrative usage of viewPager in Google play App.
            ViewPager is available through the support library. ViewPagers can animate screen slides automatically. Here's what a screen slide looks like that transitions from one screen of content to the next.In a sense, it's just a nicer way to show the user multiple tabs. It also has the ability to dynamically add and remove pages (or tabs) at anytime. Consider the idea of grouping search results by certain categories, and showing each category in a separate list. With the ViewPager, the user could then swipe left or right to see other categorized lists. ViewPager is most often used in conjunction with Fragment .PageAdapters implemented for using fragments. In this case, Fragments are "pages". Each screen that the ViewPager allows the user to scroll to is really a Fragment. By using Fragments instead of a View here, we're given a much wider range of possibilities to show in each page. We're not limited to just a List of items. This could be any collection of views and widgets we may need. You can think of PageAdapters in the same way that you think of ListAdapters. The Page Adapter's job is to supply Fragments (instead of views) to the UI for drawing.
The Demonstrative project shows the list of images which being scaled can be viewed by swiping from left to right or right to left.It can also be achieved by pressing buttons portrays the features of ViewPager.
1.Create  Android project with details as listed in the table below.
Property name
Property value
Project name
SRM_Viewpager
Package name
in.ac.srmuniv.viewpagertutorial
Activity name
MainActivity
Layout xml name
activity_main

2.Copy the code  to the file activity_main.xml in res/layout folder.
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="top"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/imagedes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center_horizontal"
                android:text="Large Text"
                android:textAppearance="?android:attr/textAppearanceLarge"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="match_parent"  
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="vertical" >

            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
            </android.support.v4.view.ViewPager>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/linearLayout2"
            android:layout_width="match_parent"   
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:orientation="horizontal" >

            <Button
                android:id="@+id/btnImagePrevious"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Previous" />

            <Button
                android:id="@+id/btnImageNext"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Next" />
        </LinearLayout>
    </FrameLayout>


</LinearLayout>
2.Copy the code  to the file imageview.xml in res/layout folder.Fragment layout.
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/ivImageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>
4.Copy the code  to the file strings.xml in res/values folder 
<resources>

    <string name="app_name">SRM_ViewPageTutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_image_pager_view">SRM Univertsity Pictures</string>

    <string-array name="imageDes">
        <item>SRM University Building</item>
        <item>SRM University Entrance</item>
        <item>SRM University Vadapalani Campus</item>
        <item>SRM University Auditoriam</item>
        <item>SRM University Hostels</item>
        <item>SRM Universsity Tech park</item>
        <item>SRM University NCR Campus</item>
    </string-array>

</resources>
5.Copy the code in MainActivity.java. Activity.
packagein.ac.srmuniv.viewpagetutorial;

import java.util.ArrayList;
import java.util.Arrays;

importandroid.content.res.Resources;
import android.os.Bundle;
importandroid.support.v4.app.FragmentActivity;
importandroid.support.v4.view.ViewPager;
importandroid.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.TextView;

importin.ac.srmuniv.viewpagetutorial.R;

public class MainActivity extends FragmentActivity implements OnClickListener,
           OnPageChangeListener {

     private Button btnImagePrevious, btnImageNext;
     private int position = 0, totalImage;
     private ViewPager viewPage;
     private TextView imagedes;
     private FragmentPagerAdapter adapter;
     privateArrayList<Integer> imageId;
     privateArrayList<String> imageDes;

     @Override
     public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           imageId = new ArrayList<Integer>();
           imageId.add(R.drawable.srm1);
           imageId.add(R.drawable.srm2);
           imageId.add(R.drawable.srm3);
           imageId.add(R.drawable.srm4);
           imageId.add(R.drawable.srm5);
           imageId.add(R.drawable.srm6);
           imageId.add(R.drawable.srm7);
           Resources res = getResources();
           String[] imageStringDes = res.getStringArray(R.array.imageDes);
           imageDes = newArrayList<String>(Arrays.asList(imageStringDes));
           viewPage = (ViewPager) findViewById(R.id.viewPager);
           imagedes = (TextView) findViewById(R.id.imagedes);
           btnImagePrevious = (Button) findViewById(R.id.btnImagePrevious);
           btnImageNext = (Button) findViewById(R.id.btnImageNext);
           totalImage = imageId.size();
           setPage(position);

           adapter = newFragmentPagerAdapter(getSupportFragmentManager(), imageId);
           viewPage.setAdapter(adapter);
           viewPage.setOnPageChangeListener(MainActivity.this);

           btnImagePrevious.setOnClickListener(this);
           btnImageNext.setOnClickListener(this);

     }

     @Override
     public void onClick(View v) {
           if (v == btnImagePrevious) {
                position--;
                viewPage.setCurrentItem(position);
           } else if (v == btnImageNext) {
                position++;
                viewPage.setCurrentItem(position);
           }
     }

     @Override
     public voidonPageScrollStateChanged(int arg0) {
     }

     @Override
     public void onPageScrolled(int arg0, float arg1, int arg2) {

     }

     @Override
     public void onPageSelected(int position) {
           this.position = position;
           setPage(position);
     }

     private void setPage(int page) {
           if (page == 0 && totalImage > 0) {
                btnImageNext.setVisibility(View.VISIBLE);
                btnImagePrevious.setVisibility(View.INVISIBLE);
                imagedes.setText(imageDes.get(page));

           } else if (page == totalImage - 1 && totalImage > 0) {
                btnImageNext.setVisibility(View.INVISIBLE);
                btnImagePrevious.setVisibility(View.VISIBLE);
                imagedes.setText(imageDes.get(page));
           } else {
                btnImageNext.setVisibility(View.VISIBLE);
                btnImagePrevious.setVisibility(View.VISIBLE);
                imagedes.setText(imageDes.get(page));
           }
     }
}
6.Copy the code in FragmentImageView.java.Fragment.
packagein.ac.srmuniv.viewpagetutorial;

importandroid.app.ProgressDialog;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
import android.os.Bundle;
importandroid.support.v4.app.Fragment;
importandroid.view.LayoutInflater;
import android.view.View;
importandroid.view.ViewGroup;
importandroid.widget.ImageView;

importin.ac.srmuniv.viewpagetutorial.R;

public class FragmentImageView extends Fragment {

     private Integer itemData;
     private Bitmap myBitmap;
     public ProgressDialog pd;
     private ImageView ivImage;

     public static FragmentImageView newInstance() {
           FragmentImageView f = new FragmentImageView();
           return f;
     }

     @Override
     public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
     }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
           View root = inflater.inflate(R.layout.imageview, container, false);
           ivImage = (ImageView) root.findViewById(R.id.ivImageView);
           setImageInViewPager();
           return root;
     }

     public void setImageList(Integer integer) {
           this.itemData = integer;
     }

     public voidsetImageInViewPager() {

           try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                myBitmap = BitmapFactory.decodeResource(getResources(), itemData,
                           options);
                if (options.outWidth > 3000 || options.outHeight > 2000) {
                     options.inSampleSize = 4;
                } else if (options.outWidth > 2000 || options.outHeight > 1500) {
                     options.inSampleSize = 3;
                } else if (options.outWidth > 1000 || options.outHeight > 1000) {
                     options.inSampleSize = 2;
                }
                options.inJustDecodeBounds = false;
                myBitmap = BitmapFactory.decodeResource(getResources(), itemData,
                           options);
                if (myBitmap != null) {
                     try {
                           if (ivImage != null) {
                                ivImage.setImageBitmap(myBitmap);
                           }
                     } catch (Exception e) {
                           e.printStackTrace();
                     }
                }
           } catch (OutOfMemoryError e) {
                e.printStackTrace();
                System.gc();
           }

     }

     @Override
     public void onDestroyView() {
           super.onDestroyView();
           if (myBitmap != null) {
                myBitmap.recycle();
                myBitmap = null;
           }
     }
}
7.Copy the code in FragmentPageAdapter.java. FragmentStatePageAdapter.
packagein.ac.srmuniv.viewpagetutorial;

import java.util.ArrayList;

importandroid.support.v4.app.Fragment;
importandroid.support.v4.app.FragmentManager;
importandroid.support.v4.app.FragmentStatePagerAdapter;
importandroid.view.ViewGroup;

public class FragmentPagerAdapter extendsFragmentStatePagerAdapter {

     privateArrayList<Integer> itemData;

     public FragmentPagerAdapter(FragmentManager fm, ArrayList<Integer> itemData) {
           super(fm);
           this.itemData = itemData;
     }

     @Override
     public int getCount() {
           return itemData.size();
     }

     @Override
     public voiddestroyItem(ViewGroup container, int position, Object object) {
           super.destroyItem(container, position, object);
     }

     @Override
     public Fragment getItem(int position) {
           FragmentImageView f = FragmentImageView.newInstance();
           f.setImageList(itemData.get(position));
           return f;
     }
}
8.No need to modify Androidmanifest.xml.
9.Run the application in the emulator. 




Figure 4 Shows First Image is displayed in viewPager Figure 5 Shows the next image is shown when user swipes the screen or press Button.
Figure 4 Shows the last slide of image is in displayed in viewPager.
CODE EXPLANATION
MainActivity extends FragmentActivity since the Activity handles Fragments.Layout of the Activity contains ViewPager.It will always occupy the entire space of the screen and will not give space for other views if other than FrameLayout is used.Here we have stacked text view(Image description) and Buttons(image navigation) along with ViewPager which the container for list of Fragments which will be navigated. FragmentPagerAdapter manages the list of Fragments(pages).In our example image resource  Ids are maintained in ArrayList in the FragmentPagerAdapter.
adapter = new FragmentPagerAdapter(getSupportFragmentManager(),imageId);
           viewPage.setAdapter(adapter);
viewPager associated with FragmentStatePageAdapter enables swipe navigation of pages(Fragments).OnPageChangeListener implemented by MainActivity can implement logic when page gets changed.
     @Override
     public voidonPageScrollStateChanged(int arg0) {
     }
     @Override
     public void onPageScrolled(int arg0, float arg1, int arg2) {

     }
     @Override
     public void onPageSelected(int position) {
           this.position = position;
           setPage(position);

     }
            In our application logic code is written to display buttons "Previous" and "Next",if  it is First image(fragment containing first image) for navigation it makes "Previous" Button invisible similarly "Next" Button will be invisible for the last navigated image( fragment containing last image).
FragmentImageView is a fragmnet class which just contains a ImageView scales down the image using BitmapFactory class to fit the screen. 



Demikianlah Artikel Android ViewPager Tutorial

Sekianlah artikel Android ViewPager Tutorial kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel Android ViewPager Tutorial dengan alamat link https://googleandroiddevelopertutorial.blogspot.com/2012/09/android-viewpager-tutorial.html

Artikel Terkait

Android ViewPager Tutorial
4/ 5
Oleh

Berlangganan

Suka dengan artikel di atas? Silakan berlangganan gratis via email