Android-ViewPager的使用

Posted Kid_TH

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android-ViewPager的使用相关的知识,希望对你有一定的参考价值。

android-ViewPager的使用


ViewPager是安卓App很常用的工具类,通常是用来设置界面导航,比如微信,QQ都是使用这种,还有就是新闻类App,很常见
比如:
这里写图片描述
这就是一个典型的例子。
复习一下这个知识点。


大致步骤和之前的ListView差不多。
1.构造适配器
2.数据源
3.加载适配器
这里写图片描述


activity_main.xml

<LinearLayout 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"
                android:orientation="vertical"
                tools:context=".MainActivity">


    <android.support.v4.view.ViewPager
        android:id="@+id/id_viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        >
    </android.support.v4.view.ViewPager>

</LinearLayout>

ViewPager使用v4的兼容包
view1-view4.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是第一个页面"/>

</LinearLayout>

自定义适配器
MyPagerAdapter.java

package com.xieth.as.againviewpagerdemo;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by YR on 2016/04/05.
 */
public class MyPagerAdapter extends PagerAdapter{

    private List<View> viewList = null;

    public MyPagerAdapter(List<View> viewList) {
        this.viewList = viewList;
    }

    // 实例化一个页卡
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        container.addView(viewList.get(position));
        return viewList.get(position);
    }

    // 销毁一个页卡
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(viewList.get(position));
    }

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

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

MainActivity.java

package com.xieth.as.againviewpagerdemo;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager pager = null;
    private MyPagerAdapter adapter = null;
    private View[] views = new View[4];
    private int[] viewId = {R.layout.view1, R.layout.view2, R.layout.view3, R.layout.view4};
    //数据源
    private List<View> viewList = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        adapter = new MyPagerAdapter(viewList);
        pager.setAdapter(adapter);

    }

    private void initViews() {
        pager = (ViewPager) findViewById(R.id.id_viewpager);

        viewList = new ArrayList<>();
        for (int i = 0; i < viewId.length; i++) {
            views[i] = View.inflate(this, viewId[i], null);
            viewList.add(views[i]);
        }
    }

}

运行:
这里写图片描述
这是一个简单的例子,然后可以在上面添加标题栏。
使用android.support.v4.view.PagerTabStrip
activity_main.xml

<LinearLayout 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"
                android:orientation="vertical"
                tools:context=".MainActivity">


    <android.support.v4.view.ViewPager
        android:id="@+id/id_viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        >
        <android.support.v4.view.PagerTabStrip
            android:id="@+id/id_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            ></android.support.v4.view.PagerTabStrip>

    </android.support.v4.view.ViewPager>

</LinearLayout>

MainActivity.java

package com.xieth.as.againviewpagerdemo;

import android.os.Bundle;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager pager = null;
    private MyPagerAdapter adapter = null;
    private View[] views = new View[4];
    private int[] viewId = {R.layout.view1, R.layout.view2, R.layout.view3, R.layout.view4};
    private String[] titleStr = {"第一页", "第二页", "第三页", "第四页"};
    //数据源
    private List<View> viewList = null;
    private List<String> titleList = null;
    // 标题
    private PagerTabStrip tab = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        adapter = new MyPagerAdapter(viewList, titleList);
        pager.setAdapter(adapter);

    }

    private void initViews() {
        pager = (ViewPager) findViewById(R.id.id_viewpager);
        tab = (PagerTabStrip) findViewById(R.id.id_tab);
        viewList = new ArrayList<>();
        titleList = new ArrayList<>();
        for (int i = 0; i < viewId.length; i++) {
            views[i] = View.inflate(this, viewId[i], null);
            viewList.add(views[i]);
        }
        for (int i = 0; i < titleStr.length; i++) titleList.add(titleStr[i]);
    }

}

运行:
这里写图片描述


可以把下面长的短线去掉:

tab.setDrawFullUnderline(false);

运行:
这里写图片描述


除了这样加载,还可以使用Fragment作为载体。
fragment1-fragment4.java
id改一下即可

package com.xieth.as.againviewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by YR on 2016/04/05.
 */
public class Fragment1 extends Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.view1, container, false);
    }
}

自定义适配器
MyFragmentPagerAdapter.java

package com.xieth.as.againviewpagerdemo;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by YR on 2016/04/05.
 */
public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    //数据源
    private List<Fragment> fragList = null;
    private List<String> titleList = null;

    public MyFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragList, List<String> titleList) {
        super(fm);
        this.fragList = fragList;
        this.titleList = titleList;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }

    @Override
    public Fragment getItem(int position) {
        return fragList.get(position);
    }

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

MainActivity.java

package com.xieth.as.againviewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager pager = null;
    private MyPagerAdapter adapter = null;
    private View[] views = new View[4];
    private int[] viewId = {R.layout.view1, R.layout.view2, R.layout.view3, R.layout.view4};
    private String[] titleStr = {"第一页", "第二页", "第三页", "第四页"};
    //数据源
    private List<View> viewList = null;
    private List<String> titleList = null;
    // 标题
    private PagerTabStrip tab = null;

    // Fragment适配器
    private MyFragmentPagerAdapter myFragmentPagerAdapter = null;

    private List<Fragment> fragList = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        tab.setDrawFullUnderline(false);

        adapter = new MyPagerAdapter(viewList, titleList);
       // pager.setAdapter(adapter);

        pager.setAdapter(myFragmentPagerAdapter);
    }

    private void initViews() {
        pager = (ViewPager) findViewById(R.id.id_viewpager);
        tab = (PagerTabStrip) findViewById(R.id.id_tab);
        fragList = new ArrayList<>();
        viewList = new ArrayList<>();
        titleList = new ArrayList<>();
        for (int i = 0; i < viewId.length; i++) {
            views[i] = View.inflate(this, viewId[i], null);
            viewList.add(views[i]);
        }
        for (int i = 0; i < titleStr.length; i++) titleList.add(titleStr[i]);

        fragList.add(new Fragment1());
        fragList.add(new Fragment2());
        fragList.add(new Fragment3());
        fragList.add(new Fragment4());

        // Frgament适配器
        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragList, titleList);
    }

}

运行:
这里写图片描述
基本上是一致的:
然后可以打印一下,获取当前页面是第几个页面:
需要实现ViewPager.OnPageChangeListener接口

@Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Toast.makeText(this, "这是第" + (position + 1) + "个页面", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

记得设置事件:

pager.setOnPageChangeListener(this);

运行:
这里写图片描述


完整代码:

package com.xieth.as.againviewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener{

    private ViewPager pager = null;
    private MyPagerAdapter adapter = null;
    private View[] views = new View[4];
    private int[] viewId = {R.layout.view1, R.layout.view2, R.layout.view3, R.layout.view4};
    private String[] titleStr = {"第一页", "第二页", "第三页", "第四页"};
    //数据源
    private List<View> viewList = null;
    private List<String> titleList = null;
    // 标题
    private PagerTabStrip tab = null;

    // Fragment适配器
    private MyFragmentPagerAdapter myFragmentPagerAdapter = null;

    private List<Fragment> fragList = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        tab.setDrawFullUnderline(false);

        adapter = new MyPagerAdapter(viewList, titleList);
       // pager.setAdapter(adapter);

        pager.setAdapter(myFragmentPagerAdapter);
        pager.setOnPageChangeListener(this);
    }

    private void initViews() {
        pager = (ViewPager) findViewById(R.id.id_viewpager);
        tab = (PagerTabStrip) findViewById(R.id.id_tab);
        fragList = new ArrayList<>();
        viewList = new ArrayList<>();
        titleList = new ArrayList<>();
        for (int i = 0; i < viewId.length; i++) {
            views[i] = View.inflate(this, viewId[i], null);
            viewList.add(views[i]);
        }
        for (int i = 0; i < titleStr.length; i++) titleList.add(titleStr[i]);

        fragList.add(new Fragment1());
        fragList.add(new Fragment2());
        fragList.add(new Fragment3());
        fragList.add(new Fragment4());

        // Frgament适配器
        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragList, titleList);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Toast.makeText(this, "这是第" + (position + 1) + "个页面", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

OK。
记录一下。


以上是关于Android-ViewPager的使用的主要内容,如果未能解决你的问题,请参考以下文章

Android-ViewPager2

Android-ViewPager源码解析与性能优化

微信小程序代码片段

webstorm代码片段的创建

使用 Git 来管理 Xcode 中的代码片段

Android课程---Android Studio使用小技巧:提取方法代码片段