글목록

2014. 4. 1.

[Android] ViewPager Example


1. activity_main.xml:
  


    
    




 2.MainActivity.java


 

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity
{
    private ViewPager mPager;

    public int[] mRes = new int[] {
            R.drawable.sing_box01, R.drawable.sing_box02, R.drawable.sing_box03,
            R.drawable.sing_box04, R.drawable.sing_box05, R.drawable.sing_box06,
            R.drawable.sing_box07, R.drawable.sing_box08, R.drawable.sing_box09,
            R.drawable.sing_box10
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        ViewPager viewPager = (ViewPager) findViewById(R.id.content_pager);
        ImageAdapter adapter = new ImageAdapter();
        viewPager.setAdapter(adapter);

    }



    class ImageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mRes.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == ((ImageView) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageResource(mRes[position]);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }


}



댓글 없음:

댓글 쓰기