首页 > 其他分享 >为ViewPager设置SimpleViewPagerIndicator

为ViewPager设置SimpleViewPagerIndicator

时间:2023-04-06 22:45:37浏览次数:47  
标签:int ViewPager private SimpleViewPagerIndicator 设置 position import android public


说到ViewPagerIndicator,网上有很多专门的开源库;
我这里重提一下,只是想试试它的实现方法;
记录下来,可以以后快速的修改迭代~~~

很简单的一个类:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleViewPagerIndicator extends LinearLayout
{

    private static final int COLOR_TEXT_NORMAL = 0xFF999999;

    private static final int COLOR_INDICATOR = Color.BLACK;

    private String[] mTitles;

    private int mTabCount;

    private int mIndicatorColor = COLOR_INDICATOR;

    private float mTranslationX;

    private Paint mPaint = new Paint();

    private int mTabWidth;

    private int oldPosition = 0;

    private ViewPager viewPager;

    public SimpleViewPagerIndicator(Context context)
    {
        this(context, null);
    }

    public SimpleViewPagerIndicator(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        mPaint.setColor(mIndicatorColor);
        mPaint.setStrokeWidth(10.0F);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        mTabWidth = w / mTabCount;
    }

    public void setTitles(String[] titles)
    {
        mTitles = titles;
        mTabCount = titles.length;
    }

    public void setIndicatorColor(int indicatorColor)
    {
        this.mIndicatorColor = indicatorColor;
    }

    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        super.dispatchDraw(canvas);
        canvas.save();
        canvas.translate(mTranslationX, getHeight() - 2);
        canvas.drawLine(0, 0, mTabWidth, 0, mPaint);
        canvas.restore();
    }

    public void setViewPager(ViewPager viewPager)
    {

        if (viewPager instanceof ViewPager)
        {
            this.viewPager = viewPager;
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
            {
                @Override
                public void onPageSelected(int position)
                {
                    View v = getChildAt(position);
                    if (v instanceof TextView)
                    {
                    	TextView oldTv = (TextView) getChildAt(oldPosition);
                    	oldTv.setTextColor(COLOR_TEXT_NORMAL);
                    	
                        TextView tv = (TextView) v;
                        tv.setTextColor(COLOR_INDICATOR);

                        oldPosition = position;
                    }
                    if (onPageChangeListener != null)
                    {
                        onPageChangeListener.onPageSelected(position);
                    }
                }

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

                @Override
                public void onPageScrollStateChanged(int state)
                {

                }
            });
        }

    }

    public void scroll(int position, float offset)
    {
        mTranslationX = getWidth() / mTabCount * (position + offset);
        invalidate();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev)
    {
        return super.dispatchTouchEvent(ev);
    }

    private void generateIndicators()
    {
        if (getChildCount() > 0)
            this.removeAllViews();
        int count = mTitles.length;

        setWeightSum(count);
        for (int i = 0; i < count; i++)
        {
            TextView tv = new TextView(getContext());
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            tv.setTag(i);
            tv.setGravity(Gravity.CENTER);
            tv.setTextColor(COLOR_TEXT_NORMAL);
            tv.setText(mTitles[i]);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            tv.setLayoutParams(lp);
            tv.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    int position = (Integer) v.getTag();
                    if (viewPager != null)
                    {
                        viewPager.setCurrentItem(position);
                    }
                    if(onItemClickListener!=null){
                    	onItemClickListener.onItemClick(v, position);
                    }
                }
            });
            addView(tv);
        }
    }

    private OnPageChangeListener onPageChangeListener;

    public void setOnPageChangeListener(OnPageChangeListener onPageChangeListener)
    {
        this.onPageChangeListener = onPageChangeListener;
    }

    public interface OnPageChangeListener
    {
        public void onPageSelected(int position);
    }

    
    private OnItemClickListener onItemClickListener;
    
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		this.onItemClickListener = onItemClickListener;
	}

	public interface OnItemClickListener
    {
        public void onItemClick(View view,int position);
    }
    /**
     * 选中当前页 。此方法一定要在setTitles(),setViewPager()之后调用!
     * 
     * @param position
     */
    public void setCurrentItem(int position)
    {
        oldPosition = position;
        generateIndicators();
        if (viewPager != null)
        {
            viewPager.setCurrentItem(position);
        }
    }

    
}




用法:


package com.example.testviewpagerindicator;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;

import com.me.view.SimpleViewPagerIndicator;

public class MainActivity extends FragmentActivity
{
    private Context context;

    private String[] titles = new String[]
    { "第1页", "第2页", "第3页", "第4页" };

    private SimpleViewPagerIndicator indicator;

    private ViewPager viewpager;

    private FragmentPagerAdapter pagerAdapter;

    private TabFragment[] fragments = new TabFragment[titles.length];

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initViews();
    }

    private void initViews()
    {
        for (int i = 0; i < titles.length; i++)
        {
            fragments[i] = (TabFragment) TabFragment.newInstance(titles[i]);
        }

        pagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager())
        {
            @Override
            public int getCount()
            {
                return titles.length;
            }

            @Override
            public Fragment getItem(int position)
            {
                return fragments[position];
            }

        };

        viewpager = (ViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter(pagerAdapter);

        indicator = (SimpleViewPagerIndicator) findViewById(R.id.indicator);
        indicator.setTitles(titles);
        indicator.setViewPager(viewpager);
        indicator.setCurrentItem(1);

        // indicator.setOnPageChangeListener(new SimpleViewPagerIndicator.OnPageChangeListener()
        // {
        //
        // @Override
        // public void onPageSelected(int position)
        // {
        // // TODO Auto-generated method stub
        // Toast.makeText(context, position + " clicked", Toast.LENGTH_SHORT).show();
        // }
        // });

    }

}




注意:使用了SimpleViewPagerIndicator之后,需要使用indicator.setOnPageChangeListener(...)监听页面的切换,不要再使用viewpager .setOnPageChangeListener(...)设置了。



最后是个Fragment:


package com.example.testviewpagerindicator;

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 TabFragment extends Fragment
{
	public static final String TITLE = "title";
	private String mTitle = "Defaut Value";
	private TextView mTextView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		if (getArguments() != null)
		{
			mTitle = getArguments().getString(TITLE);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_tab, container, false);
		mTextView = (TextView) view.findViewById(R.id.id_info);
		mTextView.setText(mTitle);
		return view;

	}

	public static TabFragment newInstance(String title)
	{
		TabFragment tabFragment = new TabFragment();
		Bundle bundle = new Bundle();
		bundle.putString(TITLE, title);
		tabFragment.setArguments(bundle);
		return tabFragment;
	}

}




主布局:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.example.testviewpagerindicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <com.me.view.SimpleViewPagerIndicator
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="#ffffffff" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:flipInterval="30"
        android:persistentDrawingCache="animation"
         />
    
</LinearLayout>





https://github.com/ogaclejapan/SmartTabLayout


http://www.open-open.com/lib/view/open1426474795101.html



一个带有回弹效果的ViewPager,这个类具体见:


http://gundumw100.iteye.com/blog/1775588




Android 高仿微信6.0主界面 带你玩转切换图标变色



Android 自定义控件玩转字体变色 打造炫酷ViewPager指示器


Android 教你打造炫酷的ViewPagerIndicator 不仅仅是高仿MIUI


Android TabLayout 库:FlycoTabLayout


http://www.open-open.com/lib/view/open1447294190257.html

标签:int,ViewPager,private,SimpleViewPagerIndicator,设置,position,import,android,public
From: https://blog.51cto.com/u_5454003/6174199

相关文章

  • 缓存式的ViewPager&和其他手势控件冲突的解决办法
    一般来说ViewPager如果有很多页的话,会加载它的上一页,当前页和下一页,当从n页以后再想回到第一页,就会再加载一次,这样第一页很多操作后的数据就会被重置,原因是在PagerAdapter的destroyItem经常会移除View,类似下面这样的代码:@Overridepublicvoiddest......
  • 带标记的ImageView,图片可以设置成圆角
    先看图这个功能可以很方便的为一张图片设置一个标记,这在促销的时候很是有效<com.mb.bgfitting.view.SimpleTagImageViewxmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/item_0"android:layout_width="80dp......
  • 通过拍照或选择本地图片并剪裁图片设置成头像
    还是直接上代码importjava.io.File;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.content.DialogInterface;importandroid.content.Intent;importandroid.graphics.Bitmap;importandroid.graphics.drawable.B......
  • 分别设置listview加载中、空数据、加载数据失败三种状态的显示
    设置listview加载中,空数据,加载数据失败三种状态的显示.基本用法:importjava.util.ArrayList;importjava.util.Arrays;importcom.kanak.emptylayout.EmptyLayout;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnCl......
  • MySQL Others--优化autocommit会话参数设置请求
    问题描述在排查QPS较高的MySQL集群过程中发现,部分MySQL集群约50%的请求为"SETautocommit=1",每次业务请求前都会执行1次"SETautocommit=1"操作,虽然单次”SETautocommit=1“操作并不会消耗过多MySQL服务器资源,但高QPS场景下频繁执行"SETautocommit=1"操作,严重浪费应用服务器和M......
  • 【Linux】wordpress后台设置
    文章目录一.个人资料1.点击右上角的个人名称:选中编辑我的个人资料2.按下图进行修改二.设置--常规选项三.文章分类一.个人资料1.点击右上角的个人名称:选中编辑我的个人资料2.按下图进行修改二.设置–常规选项三.文章分类登陆后台-文章-分类目录Linux基础,web应用,中间件,数......
  • CAD模板怎么设置?CAD模板设置技巧
    在CAD制图过程中,如果需要设置一个模板的话该如何操作呢?CAD模板怎么设置?本节CAD制图教程就和小编一起来了解一下浩辰CAD软件中设置CAD模板的相关操作技巧吧!CAD模板设置步骤:步骤一:启动浩辰CAD后,打开或者是新建一个可以作为模板的图形文件。步骤二:点击软件左上角的【G】图标,在下拉......
  • 直播平台搭建源码,XBanner设置只显示轮播图
    直播平台搭建源码,XBanner设置只显示轮播图setData()和loadImage()方法同时设置才能生效XBannerbannerView;privateList<BannerItem>bannerItems=newArrayList<>();bannerItems.clear();bannerItems.addAll(bannerItem);bannerView.setData(R.layout.xbanner_custom_layout,......
  • PDM——发动机PDM报错“Windchill 只支持标准模式下的 Internet Explorer 浏览器。请
     解决办法:通过IE8访问WindchillPDMLink10.0,出现警告提示"Windchill只支持标准模式下的浏览器".说明:详细警告提示如下注意:检测到不支持的浏览器模式。Windchill只支持标准模式下的InternetExplorer浏览器。请联系系统管理员帮助您设置浏览器。适用于 WindchillPDM......
  • echart折线图,柱状图,饼图设置颜色
    之前在做报表的时候用过echart用完也就完了,而这次在用的时候已经忘了,所以这里简单记录一下,好记性不如烂笔头!!!1、折线图修改颜色:1.xAxis:{2.'category',3.false,4.'年龄','20岁以下','30岁','40岁','50岁','60岁','60岁以上']5.},......