收藏本站 收藏本站
积木网首页 - 软件测试 - 常用手册 - 站长工具 - 技术社区
首页 > Android > Android基础 > 正文

首页 - PHP - 数据库 - 操作系统 - 游戏开发 - JS - Android - MySql - Redis - MongoDB - Win8 - Shell编程 - DOS命令 - jQuery - CSS样式 - Python - Perl

Access - Oracle - DB2 - SQLServer - MsSql2008 - MsSql2005 - Sqlite - PostgreSQL - node.js - extjs - JavaScript vbs - Powershell - Ruby

android:ViewPager与FragmentPagerAdapter

关键点

ViewPager的滑动监听,自动定时滑动,滑动时间的设置。

Code MainActivity
package net.mobctrl.viewpager;

import java.lang.reflect.Field;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
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.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    private Button btnNext;
    private Button btnAuto;

    private ViewPager viewPager;
    private TextView textView;
    private ImageView imageView;

    private MyViewPagerAdapter viewPagerAdapter;

    private String[] fragmentTexts = { "Fragment1", "Fragment2", "Fragment3" };
    private int currentPosition;

    private Handler handler;

    private boolean autoScroll = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnNext = (Button) findViewById(R.id.btn_next);
        btnAuto = (Button) findViewById(R.id.btn_auto);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        imageView = (ImageView) findViewById(R.id.iv_icon);
        textView = (TextView) findViewById(R.id.tv_show);

        btnNext.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                nextPager();
            }
        });

        btnAuto.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (autoScroll) {
                    autoScroll = false;
                } else {
                    autoScroll = true;
                    new Thread(runable).start();
                }
            }
        });

        viewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                textView.setText("current:" + position);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                    int positionOffsetPixels) {
                currentPosition = position;
                imageView.setRotation(360 * positionOffset);
                textView.setAlpha(Math.abs(positionOffset - 0.5f));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                /**
                 * SCROLL_STATE_IDLE SCROLL_STATE_DRAGGING SCROLL_STATE_SETTLING
                 */
            }
        });

        for (String text : fragmentTexts) {
            viewPagerAdapter.addOneFragment(new MyFragment()
                    .setTextContent(text));
        }

        modifyScrollerDuration(viewPager);
        handler = new Handler();

    }

    /**
     * 滑动到下一个页面
     */
    private void nextPager() {
        currentPosition++;
        viewPager.setCurrentItem(currentPosition
                % (viewPagerAdapter.getCount()), true);
    }

    /**
     * 修改滑动的时间
     * 
     * @param mPager
     */
    private void modifyScrollerDuration(ViewPager mPager) {
        try {
            Field mScroller;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(
                    mPager.getContext(), new DecelerateInterpolator());
            mScroller.set(mPager, scroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 定时滑动
     */
    public Runnable runable = new Runnable() {

        @Override
        public void run() {
            while (autoScroll) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        nextPager();
                    }
                });
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };
}
activity_main.xml
<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"
    android:background="@android:color/white" >

    <LinearLayout
        android:id="@+id/ll_panel"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_next"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="next" />

        <Button
            android:id="@+id/btn_auto"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="auto" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/ll_panel"
        android:layout_alignParentTop="true" >
    </android.support.v4.view.ViewPager>

    <TextView
        android:id="@+id/tv_show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="#7a000000"
        android:gravity="center"
        android:text="viewpage" />

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:contentDescription="@string/app_name"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
MyViewPagerAdapter
package net.mobctrl.viewpager;

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

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyViewPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyViewPagerAdapter(FragmentManager fm) {
        super(fm);
        fragments = new ArrayList<Fragment>();
    }

    @Override
    public Fragment getItem(int location) {
        if (location < 0 || location >= fragments.size()) {
            return null;
        }
        return fragments.get(location);
    }

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

    public void addOneFragment(Fragment fragment) {
        fragments.add(fragment);
        this.notifyDataSetChanged();
    }

    public void addAllFragments(List<Fragment> list) {
        fragments.addAll(fragments);
        this.notifyDataSetChanged();
    }
}
FixedSpeedScroller
package net.mobctrl.viewpager;

import android.content.Context;
import android.view.animation.Interpolator;
import android.widget.Scroller;

public class FixedSpeedScroller extends Scroller {

    private int mDuration = 800;

    public FixedSpeedScroller(Context context) {
        super(context);
    }

    public FixedSpeedScroller(Context context, Interpolator interpolator) {
        super(context, interpolator);
    }

    public FixedSpeedScroller(Context context, Interpolator interpolator,
            boolean flywheel) {
        super(context, interpolator, flywheel);
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        super.startScroll(startX, startY, dx, dy, mDuration);
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy) {
        super.startScroll(startX, startY, dx, dy, mDuration);
    }
}
MyFragment
package net.mobctrl.viewpager;

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

public class MyFragment extends Fragment {

    private TextView textView;
    private String text;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_text, null);
        textView = (TextView) view.findViewById(R.id.tv_content);
        textView.setText(text);
        return view;
    }

    public MyFragment setTextContent(String text) {
        this.text = text;
        return this;
    }

}
总结

主要是解决ViewPager的几个问题:滑动过程的监听,自动滑动,自动滑动的时间修改
查看图片

更多交流

Android开发联盟QQ群:272209595

Android:跟手滑动的布局ViewGroup
跟手滑动很多开发者对布局的跟手滑动不太了解,在此就举一个例子,看一个RelativeLayout的滑动显示原理无论是跟手滑动,还是弹入弹出动画,本质上都

Android:自定义控件的一些注意点
自定义控件的几个注意点如果自定义View需要设置一个不变的背景图,为了提高效率,你可以在构造方法中直接设置背景图片。无需在onDraw中绘制Bitmapback

android:Background线程池和UiThread线程池
由来希望在代码的任何地方,无论是在Ui线程中调用,还是Thread中调用,都能指定Runnable执行的所在的线程池。Codespackagecom.example.androidbackgroundexecuter;impor

本周排行

更新排行

强悍的草根IT技术社区,这里应该有您想要的! 友情链接:b2b电子商务
Copyright © 2010 Gimoo.Net. All Rights Rreserved  京ICP备05050695号