android自定义view 右侧字母导航
这次需求是做一个带右侧字母导航的国家地区的选择页面,这个效果在微信通讯录里就有展现,对于ios来说,直接一个控件就搞定,但是android是没有这样的控件的,所以要在android里实现这样的效果就不得不自己去自定义view了。
- 首先来看一下需要显示的效果图
这里简单说一下实现的思想,布局就是listview+一个自定义的view。父布局是framelayout,自定义view是叠在listview上面的右边。触摸字母的时候,自定义view的背景会变成黑色。支持单点、滑动选择。
下面就来讲讲怎么实现吧
首先我们先自定义view
import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.annotation.Nullable; import android.text.TextPaint; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import java.util.HashMap; import java.util.Map; //Created by lake on 2017/7/18. //右侧字母导航 public class WordNavView extends View{ //字母颜色 private int mTextColor = Color.GRAY; //字母大小 private float mTextSize = 36; //字母内容 private String[] mTextList= {"A","B","C","D","E","F","G","H","I","J","K","L" ,"M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"}; // 字母宽度 private float mTextWidth; //字母高度 private float mTextHeight; // 位置与字母关系表 private Map<Float,String> mPointMap; //手势监听 private GestureDetector mGestureDetector; //当前选择的字母 private String mCurWord = "A"; //是否显示黑色背景 private boolean isShowBlackBg =false; // 背景画笔 private Paint mBgPaint; //字母焦点监听 private OnTouchingWordChangedListener onTouchingWordChangedListener; public WordNavView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initPaint(); } //初始化画笔 private void initPaint() { mPaint = new TextPaint(); mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);//消除锯齿 mPaint.setColor(mTextColor); mPaint.setTextSize(mTextSize); mBgPaint = new Paint(); mBgPaint.setFlags(Paint.ANTI_ALIAS_FLAG);//消除锯齿 mBgPaint.setColor(Color.BLACK); mBgPaint.setStyle(Paint.Style.FILL);//充满 Paint.FontMetrics fontMetrics=mPaint.getFontMetrics(); mTextHeight = Math.abs(fontMetrics.top); mGestureDetector = new GestureDetector(getContext(),new MySimpleGestureDetector()); } // 绘图 @Override protected void onDraw(Canvas canvas) { mPointMap = new HashMap<>(); mPaint.setColor(mTextColor); if(isShowBlackBg){ RectF rectF = new RectF(getPaddingLeft(),getPaddingTop(),getPaddingLeft()+getWidth(),getPaddingTop()+getHeight()); canvas.drawRoundRect(rectF, getWidth()/2, getWidth()/2, mBgPaint); mPaint.setColor(Color.WHITE); } for (int i = 0; i < mTextList.length; i++) { mTextWidth = mPaint.measureText(mTextList[i]); canvas.drawText(mTextList[i], getPaddingLeft()+getWidth()/2-mTextWidth/2 , getPaddingTop() + getHeight()/mTextList.length*(i+1)-mTextHeight/5, mPaint); mPointMap.put(getPaddingTop() + getHeight()/mTextList.length*(i+1)-mTextHeight/5,mTextList[i]); } super.onDraw(canvas); } // 手势监听事件 @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); mGestureDetector.onTouchEvent(event); if(event.getAction()==MotionEvent.ACTION_DOWN){ //显示黑背景 isShowBlackBg = true; }else if(event.getAction()==MotionEvent.ACTION_UP){ //隐去背景 isShowBlackBg =false; } postInvalidate(); return true; } //手势监听 private class MySimpleGestureDetector extends GestureDetector.SimpleOnGestureListener{ @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float y = e2.getY(); for (Map.Entry<Float, String> entry : mPointMap.entrySet()) { if(y>=entry.getKey()-getHeight()/mTextList.length/2&&y<=entry.getKey()+getHeight()/mTextList.length/2){ if(!mCurWord.equals(entry.getValue())){ Log.e("lake",entry.getValue()); if(onTouchingWordChangedListener != null){ onTouchingWordChangedListener.onTouchingWordChanged(entry.getValue()); } } mCurWord=entry.getValue(); break; } } return super.onScroll(e1, e2, distanceX, distanceY); } @Override public boolean onSingleTapUp(MotionEvent e) { float y =e.getY(); for (Map.Entry<Float, String> entry : mPointMap.entrySet()) { if(y>=entry.getKey()-getHeight()/mTextList.length/2&&y<=entry.getKey()+getHeight()/mTextList.length/2){ Log.e("lake",entry.getValue()); if(onTouchingWordChangedListener != null){ onTouchingWordChangedListener.onTouchingWordChanged(entry.getValue()); } break; } } return super.onSingleTapUp(e); } } //向外公开的方法 字母监听 public void setOnTouchingWordChangedListener(OnTouchingWordChangedListener onTouchingWordChangedListener) { this.onTouchingWordChangedListener = onTouchingWordChangedListener; } //接口 public interface OnTouchingWordChangedListener { void onTouchingWordChanged(String s); } }
主要代码段讲解
自定义右侧字母导航view主要用到了两个view方法,一个是onDraw(),一个是onTouchEvent(MotionEvent event),下面就详细讲一下这两个方法的实现。
// 绘图
@Override
protected void onDraw(Canvas canvas) {
mPointMap = new HashMap<>();
mPaint.setColor(mTextColor);
if(isShowBlackBg){//判断是否显示黑色背景和白色字体 isShowBlackBg为true显示
//黑色矩形背景
RectF rectF = new RectF(getPaddingLeft(),getPaddingTop(),getPaddingLeft()+getWidth(),getPaddingTop()+getHeight());
//矩形椭圆化
canvas.drawRoundRect(rectF, getWidth()/2, getWidth()/2, mBgPaint);
//白色字体
mPaint.setColor(Color.WHITE);
}
//将字母数组从上到下依次显示在布局中
for (int i = 0; i < mTextList.length; i++) {
mTextWidth = mPaint.measureText(mTextList[i]);//获取每个字母的宽度
//画字母
canvas.drawText(mTextList[i], getPaddingLeft()+getWidth()/2-mTextWidth/2
, getPaddingTop() + getHeight()/mTextList.length*(i+1)-mTextHeight/5, mPaint);
//存储每个字母的起始y值 后面手势监听会用到
mPointMap.put(getPaddingTop() + getHeight()/mTextList.length*(i+1)-mTextHeight/5,mTextList[i]);
}
super.onDraw(canvas);
}
// 手势监听事件
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
mGestureDetector.onTouchEvent(event);//自定义手势监听方法
if(event.getAction()==MotionEvent.ACTION_DOWN){
//显示黑背景
isShowBlackBg = true;
}else if(event.getAction()==MotionEvent.ACTION_UP){
//隐去背景
isShowBlackBg =false;
}
postInvalidate();//刷新当前视图
return true;
}
//手势监听
private class MySimpleGestureDetector extends GestureDetector.SimpleOnGestureListener{
@Override//滑动时
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
float y = e2.getY();
for (Map.Entry<Float, String> entry : mPointMap.entrySet()) {
// 判断当前触点滑到了那个字母的y值范围,如果是某字母,则将这个字母通过接口传出去
if(y>=entry.getKey()-getHeight()/mTextList.length/2&&y<=entry.getKey()+getHeight()/mTextList.length/2){
if(!mCurWord.equals(entry.getValue())){
Log.e("lake",entry.getValue());
if(onTouchingWordChangedListener != null){
onTouchingWordChangedListener.onTouchingWordChanged(entry.getValue());
}
}
mCurWord=entry.getValue();
break;
}
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override//单击时触发的监听
public boolean onSingleTapUp(MotionEvent e) {
float y =e.getY();
for (Map.Entry<Float, String> entry : mPointMap.entrySet()) {
if(y>=entry.getKey()-getHeight()/mTextList.length/2&&y<=entry.getKey()+getHeight()/mTextList.length/2){
Log.e("lake",entry.getValue());
if(onTouchingWordChangedListener != null){
onTouchingWordChangedListener.onTouchingWordChanged(entry.getValue());
}
break;
}
}
return super.onSingleTapUp(e);
}
}
基本实现了上面两个方法,自定义字母view就实现了。是不是很简单。
然后我们来看一下布局时候怎么使用
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:background="@color/colorPrimary">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/country_code_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
<RelativeLayout
android:layout_gravity="right"
android:layout_marginBottom="60dp"
android:layout_marginTop="60dp"
android:id="@+id/sort_layout"
android:layout_width="25dp"
android:paddingRight="5dp"
android:layout_height="match_parent"
android:paddingTop="8dp"
android:layout_alignRight="@+id/expandableListView1" >
//直接以你的类名布局就可以了
<com.***.***.WordNavView
android:id="@+id/wordNavView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
</FrameLayout>
监听字母
当前页面 implements WordNavView.OnTouchingWordChangedListener
//控件实现接口
mWordNavView.setOnTouchingWordChangedListener(this);
@Override
public void onTouchingWordChanged(String s) {
//s 为当前触摸的字母 将listview的当前位置设置到对应的字母头位置就可以了
......
}
字母导航的实现就完成了,关于listview的实现我就不讲了,实现起来很简单。如果有疑问欢迎留言。
by lake