ViewPager 用法

来源:互联网 发布:电脑屏幕直播软件 免费 编辑:程序博客网 时间:2024/06/06 13:56

ViewPager 用法

@(Blog)[马克飞象|Markdown|Android]

  • ViewPager 用法
    • 布局
    • 代码

为了方便的实现不同界面之间的滑动效果,主要是实现Fragment的滑动。

布局

<RelativeLayout 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"    tools:context="com.example.focus.androidnote.viewpager.ViewPagerActivity">    <android.support.v4.view.ViewPager        android:id="@+id/pager"        android:layout_width="match_parent"        android:layout_height="match_parent" /></RelativeLayout>

代码

  • Fragment
    布局文件就不写了,直接上代码
public class TextFragment extends Fragment {    private static final String TAG = "TextFragment";    String mText;    TextView mTextTv;    public static TextFragment newInstance(String text) {        TextFragment fragment = new TextFragment();        fragment.mText = text;        return fragment;    }    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        View root = inflater.inflate(R.layout.fragment_text, container, false);        root.setBackgroundColor(Color.BLUE);        mTextTv = (TextView) root.findViewById(R.id.text_tv);        mTextTv.setText(mText);        Log.d(TAG, "onCreateView");        return root;    }}

提示
Google不建议Fragment使用有参的构造函数,所以使用newInstance()来传参数

  • Adapter
    与常用的ListView一样,ViewPager也需要使用Adapter,我们需要继承PageAdapter,不过直接继承这个的应该不多,一般我们都是使用Fragment,还可以继承FragmentPagerAdapterFragmentStatePagerAdapter,我使用的是Fragment,所以直接就继承FragmentPagerAdapter
class MyPagerAdapter extends FragmentPagerAdapter {    public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {        super(fm);    }    @Override    public int getCount() {        return mFragmentList.size();    }    @Override    public android.support.v4.app.Fragment getItem(int position) {        return mFragmentList.get(position);    }}
  • onCreate
protected ViewPager mPager;protected ArrayList<Fragment> mFragmentList;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_view_pager);    mFragmentList = new ArrayList<>();    mPager = (ViewPager) findViewById(R.id.pager);    for (int i = 0; i < 3; i++) {        Fragment fragment = TextFragment.newInstance("fragment" + i);        mFragmentList.add(fragment);    }    PagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());    mPager.setAdapter(adapter);}

只是看别人博客的时候,觉得这个好麻烦,然后自己敲了一遍后,发现也就那么回事,真的很简单。

我只是介绍了一些基础的用法,更具体的用法可以看下面的博客

参考
Android ViewPager使用详解
【移动开发】Android中三种超实用的滑屏方式汇总(ViewPager、ViewFlipper、ViewFlow)
Android中ViewPager使用FragmentPagerAdapter(底部圆点)
个人觉得第一个blog写的是最好的,后面两个感觉有点乱。

0 0
原创粉丝点击