View pager 사진 보여주기 예제, 포인터 및 애니메이션 포함
이거 참조 좋음 http://codetheory.in/android-image-slideshow-using-viewpager-pageradapter/
Android Image Slideshow using ViewPager with PagerAdapter
We’ve already discussed ViewPager
in depth in one of my earlier posts. We saw how to use it with specific PagerAdapter
implementations like FragmentPagerAdapter
and FragmentStatePagerAdapter
that works with fragments but we can also use it to inflate any other View
or ViewGroup
(with standard View hierarchy) by hooking it up with PagerAdapter
itself. In this tutorial we’ll just discuss how to how to hook a PagerAdapter
to a ViewPager
to create an Image slideshow.
Setting Up
Firstly, we’ll need to have a ViewPager
element in our layout file at res/layout/activity_main.xml
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | android:layout_width = "match_parent" android:layout_height = "match_parent" android:paddingLeft = "@dimen/activity_horizontal_margin" android:paddingRight = "@dimen/activity_horizontal_margin" android:paddingTop = "@dimen/activity_vertical_margin" android:paddingBottom = "@dimen/activity_vertical_margin" android:id = "@+id/relativeLayout" > android:id = "@+id/pager" android:layout_width = "match_parent" android:layout_height = "match_parent" > </ android.support.v4.view.ViewPager > </ RelativeLayout > |
Next, in our onCreate()
Activity method, we’ll instantiate our custom PagerAdapter
implementation and bind it to our ViewPager
object.
1 2 3 4 | mCustomPagerAdapter = new CustomPagerAdapter( this ); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mCustomPagerAdapter); |
In our Activity class we’ll have a mResources
instance variable that’ll contain an array of drawable resource IDs:
1 2 3 4 5 6 7 8 | int [] mResources = { R.drawable.first, R.drawable.second, R.drawable.third, R.drawable.fourth, R.drawable.fifth, R.drawable.sixth }; |
I downloaded six images from LoremPixel of size 400×600 and put them into the res/drawable
directory. We’ll use these images in our carousel.
Finally it’s time to write our custom pager adapter implementation that’ll do the real job of populating content pages within our ViewPager
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | class CustomPagerAdapter extends PagerAdapter { Context mContext; LayoutInflater mLayoutInflater; public CustomPagerAdapter(Context context) { mContext = context; mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mResources.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((LinearLayout) object); } @Override public Object instantiateItem(ViewGroup container, int position) { View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false ); ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView); imageView.setImageResource(mResources[position]); container.addView(itemView); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((LinearLayout) object); } } |
Let’s discuss the four methods that we’ve overridden (mandatory):
getCount()
– This method should return the number of views available, i.e., number of pages to be displayed/created in theViewPager
.instantiateItem()
– This method should create the page for the givenposition
passed to it as an argument. In our case, weinflate()
our layout resource to create the hierarchy of view objects and then set resource for theImageView
in it. Finally, the inflated view is added to the container (which should be theViewPager
) and return it as well.destroyItem()
– Removes the page from the container for the given position. We simply removedobject
usingremoveView()
but could’ve also usedremoveViewAt()
by passing it theposition
.isViewFromObject()
– The object returned byinstantiateItem()
is a key/identifier. This method checks whether the View passed to it (representing the page) is associated with that key or not. It is required by aPagerAdapter
to function properly. For our example, the implementation of this method is really simple, we just compare the two instances and return the evaluated boolean.
Here’s how res/layout/pager_item.xml
will look like which is inflated in the instantiateItem()
method:
1 2 3 4 5 6 7 8 9 10 11 | <? xml version = "1.0" encoding = "utf-8" ?> android:orientation = "vertical" android:layout_width = "match_parent" android:layout_height = "match_parent" > < ImageView android:layout_width = "match_parent" android:layout_height = "match_parent" android:id = "@+id/imageView" /> </ LinearLayout > |
Now if you go and test your app in the emulator or a device, you’ll be able to play with a nice slideshow based on ViewPager
with 6 pages each showing up an image from the drawable resources directory.
It is important to understand that as the user navigates to a particular page, the one next to it is generated by calling instantiateItem()
while the one before the previous one gets destroyed by calling destroyItem()
. This caching limit (destruction and rebuilding limit) can be specified by thesetOffscreenPageLimit()
method on the ViewPager
object which is set to 1 by default. Increasing this value to a higher number leads to a smoother navigation as far as the animations and interactions are concerned as everything is retained in memory but then it can also cause a memory overhead affecting the app’s performance. So you’ve to find the perfect balance in your case.
Hope that helps!
#########################################################################
// LookBookActivity.java import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; public class LookBookActivity extends BaseActivity implements OnPageChangeListener{ private Context mContext; private ViewPager mVpImg; private LinearLayout mLlpagePointer; private ImgagePagerAdapter pagerAdapter; private ImageLoader imageLoader; private DisplayImageOptions options; private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener(); private int mPrePosition = 0; public static void invokeActivity(Activity activity) { Intent intent = new Intent(activity, LookBookActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); activity.startActivity(intent); activity.overridePendingTransition(0,0); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; setContentView(R.layout.activity_lookbook); getIntentParam(); init(); } private void init(){ setTitle(mContext.getText(R.string.str_menu1)); // setHome(LookBookActivity.this); setBack(true); mVpImg = (ViewPager)findViewById(R.id.vp_img); mLlpagePointer = (LinearLayout)findViewById(R.id.ll_pagePointer); mVpImg.setOnPageChangeListener(this); imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoaderConfiguration.createDefault(this)); imageLoader.clearMemoryCache(); imageLoader.clearDiscCache(); options = new DisplayImageOptions.Builder() .showImageForEmptyUri(R.drawable.no_img) .showImageOnFail(R.drawable.no_img) .cacheInMemory(true) .cacheOnDisc(true) .build(); } private void getIntentParam() { // Intent intent = getIntent(); // mURL = intent.getStringExtra("url"); // url } @Override protected void onResume() { super.onResume(); mContext = this; setMenu(LookBookActivity.this, R.id.btn_menu_look); getImgList(); // TODO } private void getImgList() { ArrayListlist = new ArrayList (); list.add("http://spnimage.edaily.co.kr/images/photo/files/NP/S/2014/03/PS14030600349.jpg"); list.add("http://www.funsw.com/content/image/2014/03/04/20140304020032_0.jpg"); list.add("http://news20.busan.com/content/image/2014/03/04/20140304000154_0.jpg"); pagerAdapter = new ImgagePagerAdapter(list); mVpImg.setAdapter(pagerAdapter); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onStop() { super.onStop(); } @Override public void onBackPressed() { super.onBackPressed(); } class ImgagePagerAdapter extends PagerAdapter{ private ArrayList mList; private int mCnt; public ImgagePagerAdapter(ArrayList list){ this.mList = list; ImageView imgView = null; // mCnt = (int)Math.ceil((double)mList.size()/3);//화면 당 3개의 이미지를 표현하기 위해 화면 수를 구한다. mCnt = mList.size(); mLlpagePointer.removeAllViews(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); for(int i=0; i 1){ // mRightArrow.setVisibility(View.VISIBLE); // } } @Override public int getCount() { return mCnt; } /** * 각 페이지 정의 */ @Override public Object instantiateItem(View pager, int position) { LinearLayout v = (LinearLayout)View.inflate(mContext, R.layout.lookbook_detail_dp_img, null); // 3개씩 보여주기 // for(int i=position*3; (i displayedImages = Collections.synchronizedList(new LinkedList ()); @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { if (loadedImage != null) { ImageView imageView = (ImageView) view; boolean firstDisplay = !displayedImages.contains(imageUri); if (firstDisplay) { FadeInBitmapDisplayer.animate(imageView, 200); displayedImages.add(imageUri); } } } } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageSelected(int position) { mLlpagePointer.getChildAt(mPrePosition).setBackgroundResource(R.drawable.circle_off); mLlpagePointer.getChildAt(position).setBackgroundResource(R.drawable.circle_on); this.mPrePosition = position; } class PointerClickListener implements OnClickListener{ private int mItemId; public PointerClickListener(int itemId){ this.mItemId = itemId; } @Override public void onClick(View v) { mVpImg.setCurrentItem(mItemId); } } }
// activity_lookbook.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff">
<include layout="@layout/titlebar"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/vp_img"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_pagePointer"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="51dp"
android:gravity="bottom"
android:orientation="vertical" >
<include layout="@layout/bottombar"/>
</LinearLayout>
</LinearLayout>
// lookbook_detail_dp_img.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center" >
<ImageView
android:id="@+id/dp_img_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:background="#c2c2c2"
/>
<!-- <ImageView -->
<!-- android:id="@+id/dp_img_2" -->
<!-- android:layout_width="178dp" -->
<!-- android:layout_height="178dp" -->
<!-- android:scaleType="fitXY" -->
<!-- android:padding="1dp" -->
<!-- android:layout_marginLeft="5dp" -->
<!-- android:background="#c2c2c2" -->
<!-- android:visibility="gone" -->
<!-- /> -->
<!-- <ImageView -->
<!-- android:id="@+id/dp_img_3" -->
<!-- android:layout_width="178dp" -->
<!-- android:layout_height="178dp" -->
<!-- android:scaleType="fitXY" -->
<!-- android:padding="1dp" -->
<!-- android:layout_marginLeft="5dp" -->
<!-- android:background="#c2c2c2" -->
<!-- android:visibility="visible" -->
<!-- /> -->
</LinearLayout>
'안드로이드 개발 팁' 카테고리의 다른 글
android calendar 사용 예 (0) | 2014.03.12 |
---|---|
android 간단한 Custom Dialog 예제 (0) | 2014.03.12 |
android getTag, setTag를 이용하여 listview에 버튼 이벤트 받기 (0) | 2014.03.05 |
android drawable resources (tile mode, selector 등등) (0) | 2014.02.20 |
android menu drawer library (0) | 2014.02.19 |