我是不会滴,但是看了一些大神写的,我修改了一下,大家可以参照参照
一,自定义Mytabpageindicator,直接贴代码了,具体的在代码中有注释
package com.wangy.mytabpageindicator.Mytabpageindicator; import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView; import com.wangy.mytabpageindicator.R;
import com.wangy.mytabpageindicator.util.ScreenUtils; import java.util.List; /**
* Created by xhb on 2016/11/30.
*/
public class Mytabpageindicator extends LinearLayout {
/**
* 绘制三角形的画笔
*/
private Paint mPaint;
/**
* path构成一个三角形
*/
private Path mPath;
/**
* 三角形的宽度
*/
private int mTriangleWidth;
/**
* 三角形的高度
*/
private int mTriangleHeight; /**
* 三角形的宽度为单个Tab的1/6
*/
private static final float RADIO_TRIANGEL = 1.0f / 6;
/**
* 三角形的最大宽度
*/
private final int DIMENSION_TRIANGEL_WIDTH = (int) (getScreenWidth() / 3 * RADIO_TRIANGEL); /**
* 初始时,三角形指示器的偏移量
*/
private int mInitTranslationX;
/**
* 手指滑动时的偏移量
*/
private float mTranslationX; /**
* 默认的Tab数量
*/
private static final int COUNT_DEFAULT_TAB = 4;
/**
* tab数量
*/
private int mTabVisibleCount = COUNT_DEFAULT_TAB; /**
* tab上的内容
*/
private List<String> mTabTitles;
/**
* 与之绑定的ViewPager
*/
public ViewPager mViewPager; /**
* 标题正常时的颜色
*/
private static final int COLOR_TEXT_NORMAL = 0x77FFFFFF;
/**
* 标题选中时的颜色
*/
private static final int COLOR_TEXT_HIGHLIGHTCOLOR = 0xFFFFFFFF; public Mytabpageindicator(Context context)
{
this(context, null);
} public Mytabpageindicator(Context context, AttributeSet attrs)
{
super(context, attrs); // 获得自定义属性,tab的数量
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ViewPagerIndicator);
mTabVisibleCount = a.getInt(R.styleable.ViewPagerIndicator_item_count,
COUNT_DEFAULT_TAB);
if (mTabVisibleCount < 0)
mTabVisibleCount = COUNT_DEFAULT_TAB;
a.recycle(); // 初始化画笔
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.parseColor("#ffffffff"));
mPaint.setStyle(Paint.Style.FILL);
mPaint.setPathEffect(new CornerPathEffect(3)); } /**
* 绘制指示器
*/
@Override
protected void dispatchDraw(Canvas canvas)
{
canvas.save();
// 画笔平移到正确的位置
canvas.translate(mInitTranslationX + mTranslationX, getHeight() + 1);
canvas.drawPath(mPath, mPaint);
canvas.restore(); super.dispatchDraw(canvas);
} /**
* 初始化三角形的宽度
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
mTriangleWidth = (int) (w / mTabVisibleCount * RADIO_TRIANGEL);// 1/6 of
// width
mTriangleWidth = Math.min(DIMENSION_TRIANGEL_WIDTH, mTriangleWidth); // // 初始化三角形
// initTriangle();
//初始化矩形
initrectangle(); // 初始时的偏移量
mInitTranslationX = getWidth() / mTabVisibleCount / 2 - mTriangleWidth
/ 2;
} /**
* 设置可见的tab的数量
*
* @param count
*/
public void setVisibleTabCount(int count)
{
this.mTabVisibleCount = count;
} /**
* 设置tab的标题内容 可选,可以自己在布局文件中写死
*
* @param datas
*/
public void setTabItemTitles(List<String> datas)
{
// 如果传入的list有值,则移除布局文件中设置的view
if (datas != null && datas.size() > 0)
{
this.removeAllViews();
this.mTabTitles = datas; for (String title : mTabTitles)
{
// 添加view
addView(generateTextView(title));
}
// 设置item的click事件
setItemClickEvent();
} } /**
* 对外的ViewPager的回调接口
*
* @author zhy
*
*/
public interface PageChangeListener
{
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels); public void onPageSelected(int position); public void onPageScrollStateChanged(int state);
} // 对外的ViewPager的回调接口
private PageChangeListener onPageChangeListener; // 对外的ViewPager的回调接口的设置
public void setOnPageChangeListener(PageChangeListener pageChangeListener)
{
this.onPageChangeListener = pageChangeListener;
} // 设置关联的ViewPager
public void setViewPager(ViewPager mViewPager, int pos)
{
this.mViewPager = mViewPager; mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
@Override
public void onPageSelected(int position)
{
// 设置字体颜色高亮
resetTextViewColor();
highLightTextView(position); // 回调
if (onPageChangeListener != null)
{
onPageChangeListener.onPageSelected(position);
}
} @Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels)
{
// 滚动
scroll(position, positionOffset); // 回调
if (onPageChangeListener != null)
{
onPageChangeListener.onPageScrolled(position,
positionOffset, positionOffsetPixels);
} } @Override
public void onPageScrollStateChanged(int state)
{
// 回调
if (onPageChangeListener != null)
{
onPageChangeListener.onPageScrollStateChanged(state);
} }
});
// 设置当前页
mViewPager.setCurrentItem(pos);
// 高亮
highLightTextView(pos);
} /**
* 高亮文本
*
* @param position
*/
protected void highLightTextView(int position)
{
View view = getChildAt(position);
if (view instanceof TextView)
{
((TextView) view).setTextColor(COLOR_TEXT_HIGHLIGHTCOLOR);
} } /**
* 重置文本颜色
*/
private void resetTextViewColor()
{
for (int i = 0; i < getChildCount(); i++)
{
View view = getChildAt(i);
if (view instanceof TextView)
{
((TextView) view).setTextColor(COLOR_TEXT_NORMAL);
}
}
} /**
* 设置点击事件
*/
public void setItemClickEvent()
{
int cCount = getChildCount();
for (int i = 0; i < cCount; i++)
{
final int j = i;
View view = getChildAt(i);
view.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mViewPager.setCurrentItem(j);
}
});
}
} /**
* 根据标题生成我们的TextView
*
* @param text
* @return
*/
private TextView generateTextView(String text)
{
TextView tv = new TextView(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.width = getScreenWidth() / mTabVisibleCount;
tv.setGravity(Gravity.CENTER);
tv.setTextColor(COLOR_TEXT_NORMAL);
tv.setText(text);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tv.setLayoutParams(lp);
return tv;
} /**
* 初始化三角形指示器
*/
private void initTriangle()
{
mPath = new Path(); mTriangleHeight = (int) (mTriangleWidth / 2 / Math.sqrt(2));
mPath.moveTo(0, 0);
mPath.lineTo(mTriangleWidth, 0);
mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
mPath.close();
} /**
* 指示器跟随手指滚动,以及容器滚动
*
* @param position
* @param offset
*/
public void scroll(int position, float offset)
{
/**
* <pre>
* 0-1:position=0 ;1-0:postion=0;
* </pre>
*/
// 不断改变偏移量,invalidate
mTranslationX = getWidth() / mTabVisibleCount * (position + offset); int tabWidth = getScreenWidth() / mTabVisibleCount; // 容器滚动,当移动到倒数最后一个的时候,开始滚动,这边的1 也可以改成2
if (offset > 0 && position >= (mTabVisibleCount - 1)
&& getChildCount() > mTabVisibleCount)
{
if (mTabVisibleCount != 1)
{
this.scrollTo((position - (mTabVisibleCount - 1)) * tabWidth
+ (int) (tabWidth * offset), 0);
} else
// 为count为1时 的特殊处理
{
this.scrollTo(
position * tabWidth + (int) (tabWidth * offset), 0);
}
} invalidate();
} /**
* 设置布局中view的一些必要属性;如果设置了setTabTitles,布局中view则无效
*/
@Override
protected void onFinishInflate()
{
Log.e("TAG", "onFinishInflate");
super.onFinishInflate(); int cCount = getChildCount(); if (cCount == 0)
return; for (int i = 0; i < cCount; i++)
{
View view = getChildAt(i);
LinearLayout.LayoutParams lp = (LayoutParams) view
.getLayoutParams();
lp.weight = 0;
lp.width = getScreenWidth() / mTabVisibleCount;
view.setLayoutParams(lp);
}
// 设置点击事件
setItemClickEvent(); } /**
* 获得屏幕的宽度
*
* @return
*/
public int getScreenWidth()
{
WindowManager wm = (WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
} // /**
// * path构成一个三角形
// */
// private Path mPath;
// /**
// * 三角形的宽度
// */
// private int mTriangleWidth;
// /**
// * 三角形的高度
// */
// private int mTriangleHeight;
//
// /**
// * 三角形的宽度为单个Tab的1/6
// */
// private static final float RADIO_TRIANGEL = 1.0f / 6;
// /**
// * 三角形的最大宽度
// */
// private final int DIMENSION_TRIANGEL_WIDTH = (int) (getScreenWidth() / 3 * RADIO_TRIANGEL);
//
//
// /**
// * 初始时,三角形指示器的偏移量
// */
// private int mInitTranslationX;
// /**
// * 手指滑动时的偏移量
// */
// private float mTranslationX;
// /**
// * 默认的Tab数量
// */
// private static final int COUNT_DEFAULT_TAB = 4;
// /**
// * tab数量
// */
// private int count = COUNT_DEFAULT_TAB;
// /**
// * tab上的内容
// */
// private List<String> mTabTitles;
// /**
// * 与之绑定的ViewPager
// */
// public ViewPager mViewPager;
// /**
// * 标题正常时的颜色
// */
// private static final int COLOR_TEXT_NORMAL = 0x77FFFFFF;
// /**
// * 标题选中时的颜色
// */
// private static final int COLOR_TEXT_HIGHLIGHTCOLOR = 0xFFFFFFFF;
// private Paint mpaint;
//
// public Mytabpageindicator(Context context) {
// this(context, null);
// }
//
// public Mytabpageindicator(Context context, AttributeSet attrs) {
// super(context, attrs);
//
// TypedArray arry = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
//
// count = arry.getInt(R.styleable.ViewPagerIndicator_item_count, COUNT_DEFAULT_TAB);
// if (count < 0) {
// count = COUNT_DEFAULT_TAB;
// }
// arry.recycle();
// // 初始化画笔
// mpaint = new Paint();
// //抗锯齿
// mpaint.setAntiAlias(true);
// mpaint.setColor(Color.RED);
// //设置知否填充
// mpaint.setStyle(Paint.Style.FILL);
// //连线之间转角处的圆滑程度
// mpaint.setPathEffect(new CornerPathEffect(3));
// }
//
// /**
// * 设置布局中view的一些必要属性;如果设置了setTabTitles,布局中view则无效
// */
// @Override
// protected void onFinishInflate() {
// super.onFinishInflate();
// int childcount = getChildCount();
// if (childcount == 0)
// return;
// for (int i = 0; i < childcount; i++) {
// View view = getChildAt(i);
// LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
// lp.weight = 0;
// lp.width = getScreenWidth() / count;
// view.setLayoutParams(lp);
// }
//
// // 设置点击事件
// setItemClickEvent();
// }
//
// // 设置点击事件
// private void setItemClickEvent() {
// int childcount = getChildCount();
// for (int i = 0; i < childcount; i++) {
// final int j = i;
// View view = getChildAt(i);
// view.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// mViewPager.setCurrentItem(j);
// }
// });
// }
// }
//
// /**
// * 初始化三角形的宽度
// * onSizeChanged,我们主要是确定三角形的宽度和Path去构造这个三角形。
// * <p/>
// * 默认的我们的三角形的底边的宽度为,每个Tab宽度的1/6;当然有个上限是 (int) (getScreenWidth() / 3 * RADIO_TRIANGEL);【RADIO_TRIANGEL = 1.0f / 6】
// * <p/>
// * 这个其实无所谓,主要为了屏幕适配,你可以抽取为自定义属性让用户去设置;
// * <p/>
// * initTriangle()中用Path去构造了一个三角形,这个很简单了~~
// * <p/>
// * 这里还初始化了mInitTranslationX,因为一开始显示的就在第一个Tab的中间位置。
// * <p/>
// * 三角形初始化完成了,是不是应该去看看它在哪进行绘制的~~
// */
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// mTriangleWidth = (int) (w / count * RADIO_TRIANGEL);// 1/6 of
// // width
// mTriangleWidth = Math.min(DIMENSION_TRIANGEL_WIDTH, mTriangleWidth);
// //初始化三角形
// initTriangle();
//// //初始化矩形
//// initrectangle();
// // 初始时的偏移量
// mInitTranslationX = getWidth() / count / 2 - mTriangleWidth
// / 2;
// }
//
// /**
// * 初始化三角形指示器
// */
// private void initTriangle() {
// mPath = new Path();
// mTriangleHeight = (int) (mTriangleWidth / 2 / Math.sqrt(2));
// mPath.moveTo(0, 0);
// mPath.lineTo(mTriangleWidth, 0);
// mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
// mPath.close();
// }
/**
* 初始化矩形指示器
*/
private int RECTANGLE_SCALE=40;
private void initrectangle() {
mTriangleWidth=getScreenWidth()/mTabVisibleCount;
mPath = new Path();
mTriangleHeight =getHeight()/10;
mPath.moveTo(0, 0);
mPath.lineTo(mTriangleWidth, 0);
mPath.lineTo(mTriangleWidth, -mTriangleHeight);
mPath.lineTo(0, -mTriangleHeight);
mPath.close();
} }
二、接下来就是直接使用了
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<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"
xmlns:tabstyle="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<com.wangy.mytabpageindicator.Mytabpageindicator.Mytabpageindicator
android:id="@+id/id_indicator"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@drawable/bg_black"
android:orientation="horizontal"
tabstyle:item_count="4" > </com.wangy.mytabpageindicator.Mytabpageindicator.Mytabpageindicator> <android.support.v4.view.ViewPager
android:id="@+id/id_vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</android.support.v4.view.ViewPager> </LinearLayout>
mainActivity:
package com.wangy.mytabpageindicator; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window; import com.wangy.mytabpageindicator.Mytabpageindicator.Mytabpageindicator; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class MainActivity extends AppCompatActivity { private Mytabpageindicator mytabpageindicato;
private ViewPager viewPager;
private List<String> mDatas = Arrays.asList("短信1", "短信2", "短信3", "短信4",
"短信5", "短信6", "短信7", "短信8", "短信9");
// private List<String> mDatas = Arrays.asList("短信", "收藏", "推荐");
private List<Fragment> mTabContents = new ArrayList<Fragment>();
private FragmentPagerAdapter fragmentPagerAdapter; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initview();
initData();
//设置Tab上的标题
mytabpageindicato.setTabItemTitles(mDatas);
viewPager.setAdapter(fragmentPagerAdapter);
//设置关联的ViewPager
mytabpageindicato.setViewPager(viewPager,0);
}
private void initData(){
for (String data:mDatas){
VpFragment vpFragment=VpFragment.newInstance(data);
mTabContents.add(vpFragment);
} fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mTabContents.get(position);
} @Override
public int getCount() {
return mTabContents.size();
}
};
}
private void initview(){
mytabpageindicato = (Mytabpageindicator)findViewById(R.id.id_indicator);
viewPager = (ViewPager)findViewById(R.id.id_vp);
}
}
里面用到了:
vpFragment:
package com.wangy.mytabpageindicator; import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; /**
* Created by xhb on 2016/12/1.
*/
public class VpFragment extends Fragment {
public static final String BUNDLE_TITLE = "title";
private String mTitle = "DefaultValue"; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = getArguments();
if (bundle != null) {
mTitle = bundle.getString(BUNDLE_TITLE);
}
TextView textView = new TextView(getActivity());
textView.setText(mTitle);
textView.setGravity(Gravity.CENTER);
return textView;
} public static VpFragment newInstance(String mTitle) {
Bundle bundle = new Bundle();
bundle.putString(BUNDLE_TITLE, mTitle);
VpFragment vpFragment = new VpFragment();
vpFragment.setArguments(bundle);
return vpFragment;
}
}
ScreenUtils:
package com.wangy.mytabpageindicator.util; import android.content.Context;
import android.view.WindowManager; /**
* Created by xhb on 2016/12/1.
*/
public class ScreenUtils {
@SuppressWarnings("deprecation")
public static int[] getScreenDispaly(Context context){
WindowManager wm=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
int width=wm.getDefaultDisplay().getWidth();//手机屏幕的宽度
int height=wm.getDefaultDisplay().getHeight();//手机屏幕的高度
int result[] = {width,height};
return result;
}
}