实现Swipe View

一)实现方法

使用ViewPager组件来创建swipe view.   ViewPager是一个布局组件,它的每个子页面是单独的一页(或单独的一个tab).

使用方法如下:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

通过将上述布局与PagerAdapter关联, 插入子View。PagerAdapter有两个子类可供使用:

1)FragmentPagerAdapter

      适用于页数固定且较少的情况。

2)FragmentStatePagerAdapter

      适用于页数不确定的情况,在用户翻页时会销毁fragment,减少内存使用。

使用代码如下:

public class ImageDetailActivity extends FragmentActivity{
    
    private static final String IMAGE_CACHE_DIR = "images";
    
    ViewPager mPager;
    ImagePagerAdapter mAdapter;
    ImageFetcher mImageFetcher;
    public static final String EXTRA_IMAGE = "extra_image";

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.image_detail_pager);
        mPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), Images.imageUrls.length);
        mPager.setAdapter(mAdapter);
        mPager.setOffscreenPageLimit(2);
        
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels;
        mImageFetcher = new ImageFetcher(this, width > height? height : width);
        ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
        cacheParams.setMemCacheSizePercent(0.25f);
        mImageFetcher.addImageCache(getFragmentManager(), cacheParams);
        
        int position = getIntent().getIntExtra(EXTRA_IMAGE, -1);
        if (position != -1) {
            mPager.setCurrentItem(position);
        }
    }


    public ImageFetcher getImageFetcher() {
        return mImageFetcher;
    }
 
    /**
     * The main adapter that backs the ViewPager. A subclass of FragmentStatePagerAdapter as there
     * could be a large number of items in the ViewPager and we don't want to retain them all in
     * memory at once but create/destroy them on the fly.
     */
    private class ImagePagerAdapter extends FragmentStatePagerAdapter {


        private int mSize;

        public ImagePagerAdapter(FragmentManager fm, int size) {
            super(fm);
            mSize = size;
        }

        @Override
        public Fragment getItem(int position) {
            return ImageDetailFragment.newInstance(Images.imageUrls[position]);
        }


        @Override
        public int getCount() {
            return mSize;
        }            
    }
}


public class ImageDetailFragment extends Fragment {


    public static String ARG_INDEX ="extra_image_data";
    private String mImageUrl;
    private ImageView mImageView;
    private ImageFetcher mImageFetcher;

    public static ImageDetailFragment newInstance(String imageurls) {
      final ImageDetailFragment fragment = new ImageDetailFragment();
      Bundle args = new Bundle();
      args.putString(ARG_INDEX, imageurls);
      fragment.setArguments(args);
      return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageUrl = getArguments() != null? getArguments().getString(ARG_INDEX) : null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.image_detail_fragment, container, false);
        mImageView= (ImageView) v.findViewById(R.id.imageview); 
        return v;
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() instanceof ImageDetailActivity) {
            mImageFetcher = ((ImageDetailActivity) getActivity()).getImageFetcher();
            mImageFetcher.loadImage(mImageUrl, mImageView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mImageView != null) {
            ImageWorker.cancelWork(mImageView);
            mImageView.setImageDrawable(null);
        }
    }

    public ImageDetailFragment() {
        super();
    }
}

二)添加Tab到Action Bar

使用ActionBar创建tabs,需要先设置NAVIGATION_MODE_TABS,然后创建ActionBar.Tab的实例,并为每个实例提供ActionBar.TabListener接口。

代码如下:

@Override
public void onCreate(Bundle savedInstanceState){
    final ActionBar actionBar= getActionBar();
    ...

    // Specify thattabs should be displayed in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create a tablistener that is called when the user changes tabs.
    ActionBar.TabListener tabListener=new ActionBar.TabListener(){
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft){
            // show the given tab
        }

        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft){
            // hide the given tab
        }

        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft){
            // probably ignore this event
        }
    };

    // Add 3 tabs,specifying the tab's text and TabListener
    for (int i=0; i<3; i++){
        actionBar.addTab(
                actionBar.newTab()
                       .setText("Tab "+(i + 1))
                       .setTabListener(tabListener));
    }
}

Action bar导航模式已经在API21版本后Deprecated,可以考虑使用其他的导航模式来替代,参见官网: common navigation patterns  

三)随View的滑动改变Tabs

1)用户选择Tab时,通过setCurrentItem()显示VIewPager里相应的页面,代码如下:

@Override
public void onCreate(Bundle savedInstanceState){
    ...

    // Create a tablistener that is called when the user changes tabs.
    ActionBar.TabListener tabListener=newActionBar.TabListener(){
        public void onTabSelected(ActionBar.Tab tab,FragmentTransaction ft){
            // When the tab is selected, switch to the
            // corresponding page in the ViewPager.
            mViewPager.setCurrentItem(tab.getPosition());
        }
        ...
    };
}

2)通过ViewPager.OnPageChangeListener接口实现:滑动ViewPager时,选择相应的Tab,代码如下:

@Override
public void onCreate(Bundle savedInstanceState){
    ...

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOnPageChangeListener(
            new ViewPager.SimpleOnPageChangeListener(){
                @Override
                public void onPageSelected(int position){
                    // When swiping between pages, selectthe
                    // corresponding tab.
                   getActionBar().setSelectedNavigationItem(position);
                }
            });
    ...
}

注: public void setOnPageChangeListener (ViewPager.OnPageChangeListener listener)已经deprecated,可以使用addOnPageChangeListener(OnPageChangeListener) 和removeOnPageChangeListener(OnPageChangeListener) 来替代。

四)使用标题条代替Tab

1)添加PagerTitleStrip

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <android.support.v4.view.PagerTitleStrip
        android:id ="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"

        android:paddingBottom="4dp"/>
    </android.support.v4.view.ViewPager>

2)Adapter添加:

        @Override
        public CharSequence getPageTitle(int position) {
            return "OBJECT" + (position + 1);
        }

效果如下图:

实现Swipe View_第1张图片


你可能感兴趣的:(实现Swipe View)