仿IOS 带字母索引的滑轮控件

简介: 仿IOS 带字母索引的滑轮控件

效果大概就是这样,右边是字母索引效果

image.png

做开发的时候,经常碰到产品经理设计出来的界面是参考IOS控件设计出来的 ,比如上图效果  ios有个控件是UIPickerView  就是可以上下滑动 并有些3d效果,非常炫。


但是android并没有提供这样的原生控件支持,所以需要通过其他方式实现类似效果。上图就是我开发中用到的一个效果。


话不多说 ,直接上代码:


Activity

package com.example.picscrollview;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.example.picscrollview.PickerScrollView.onSelectListener;
import com.example.test.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener  {
  Boolean state_pressed = true;
  private String cities[] ={"北京版", "天津版", "上海版", "重庆版", "河北版", "山西版", "辽宁版", "吉林版", "黑龙江版", "江苏版", "浙江版", "安徽版",
      "福建版", "江西版", "山东版", "河南版", "湖北版", "湖南版", "广东版", "甘肃版", "四川版", "贵州版", "海南版", "云南版",
      "青海版", "陕西版", "广西版", "西藏版", "宁夏版", "新疆版", "内蒙古版", "澳门版", "香港版", "台湾版","全国版"}; 
  private String[] id = { "1", "2", "3", "4", "5", "6" ,"7","8","9","10","11","12","13","14","15","16", 
      "17", "18", "19", "20", "21", "22" ,"23","24","25","26","27","28","29","30","31","32","33","34","35"};
  private PickerScrollView pickerscrlllview; // 滚动选择器
  private List<Pickers> list; // 滚动选择器数据
  private CharacterParser mCharacterParser;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    initData();
  }
  public void initView() {
    LetterSideBar letterSideBar = (LetterSideBar) findViewById(R.id.cs_letter_sb);
    letterSideBar
        .setOnTouchingLetterChangedListener(new LetterSideBar.OnTouchingLetterChangedListener() {
          @Override
          public void onTouchingLetterChanged(String letter) {
            int jumpPos = getPositionForSection(letter.charAt(0));
            pickerscrlllview.setSelected(jumpPos);
          }
        });
    pickerscrlllview = (PickerScrollView) findViewById(R.id.pickerscrlllview);
    pickerscrlllview.setOnSelectListener(pickerListener);
    findViewById(R.id.location_confirm_btn).setOnClickListener(this);
  }
  private void initData() {
    mCharacterParser = CharacterParser.getInstance();
    list = filledData();
        PinyinComparator pinyinComparator = new PinyinComparator();
        Collections.sort(list, pinyinComparator);
    pickerscrlllview.setData(list);
    pickerscrlllview.setSelected(0);
  }
  @Override
  protected void onResume() {
    super.onResume();
  }
  public void onPause() {
    super.onPause();
  }
   private List<Pickers> filledData() {
      List<Pickers>  sortList = new ArrayList<Pickers>();
          for (int i = 0, n = cities.length; i < n; i++) {
            Pickers picker = new Pickers();
            picker.setShowConetnt(cities[i]);
            picker.setShowId(id[i]);
              String pinyin = mCharacterParser.getSelling(cities[i]);
              picker.setPinyin(pinyin);
              String sortString = pinyin.substring(0, 1).toUpperCase();
              if (sortString.matches("[A-Z]")) {
                picker.setSortLetter(sortString.toUpperCase());
              } else {
                picker.setSortLetter("#");
              }
              sortList.add(picker);
          }
          return sortList;
      }
      public int getPositionForSection(int section) {
          for (int i = 0; i < list.size(); i++) {
              String sortStr = list.get(i).getSortLetter();
              char firstChar = sortStr.toUpperCase().charAt(0);
              if (firstChar == section) {
                  return i;
              }
          }
          return -1;
      }
  onSelectListener pickerListener = new onSelectListener() {
    @Override
    public void onSelect(Pickers pickers) {
      Toast.makeText(MainActivity.this, pickers.getShowConetnt(), Toast.LENGTH_LONG).show();
    }
  };
  @Override
  public void onBackPressed() {
    super.onBackPressed();
  }
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    default:
      break;
    }
  }
}

自定义滑动view

package com.example.picscrollview;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.example.test.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
 * 自定义滚动选择器
 * 
 * @author zlw
 *
 */
@SuppressLint({ "HandlerLeak", "ClickableViewAccessibility" })
public class PickerScrollView extends View {
  public static final String TAG = "PickerView";
  /**
   * text之间间距和minTextSize之比
   */
  public static final float MARGIN_ALPHA = 2.8f;
  /**
   * 自动回滚到中间的速度
   */
  public static final float SPEED = 2;
  private List<Pickers> mDataList;
  /**
   * 选中的位置,这个位置是mDataList的中心位置,一直不变
   */
  private int mCurrentSelected;
  private Paint mPaint;
  private float mMaxTextSize = 14;
  private float mMinTextSize = 6;
  private float mMaxTextAlpha = 255;
  private float mMinTextAlpha = 120;
  private int mColorText = 0x333333;
  private int mViewHeight;
  private int mViewWidth;
  private float mLastDownY;
  /**
   * 滑动的距离
   */
  private float mMoveLen = 0;
  private boolean isInit = false;
  private onSelectListener mSelectListener;
  private Timer timer;
  private MyTimerTask mTask;
  Handler updateHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      if (Math.abs(mMoveLen) < SPEED) {
        mMoveLen = 0;
        if (mTask != null) {
          mTask.cancel();
          mTask = null;
          performSelect();
        }
      } else
        // 这里mMoveLen / Math.abs(mMoveLen)是为了保有mMoveLen的正负号,以实现上滚或下滚
        mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
      invalidate();
    }
  };
  public PickerScrollView(Context context) {
    super(context);
    init();
  }
  public PickerScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }
  public void setOnSelectListener(onSelectListener listener) {
    mSelectListener = listener;
  }
  private void performSelect() {
    if (mSelectListener != null)
      mSelectListener.onSelect(mDataList.get(mCurrentSelected));
  }
  public void setData(List<Pickers> datas) {
    mDataList = datas;
    mCurrentSelected = datas.size() / 2;
    invalidate();
  }
  /**
   * 选择选中的item的index
   * 
   * @param selected
   */
  public void setSelected(int selected) {
    mCurrentSelected = selected;
    int distance = mDataList.size() / 2 - mCurrentSelected;
    if (distance < 0)
      for (int i = 0; i < -distance; i++) {
        moveHeadToTail();
        mCurrentSelected--;
      }
    else if (distance > 0)
      for (int i = 0; i < distance; i++) {
        moveTailToHead();
        mCurrentSelected++;
      }
    invalidate();
  }
  /**
   * 选择选中的内容
   * 
   * @param mSelectItem
   */
  public void setSelected(String mSelectItem) {
    for (int i = 0; i < mDataList.size(); i++)
      if (mDataList.get(i).equals(mSelectItem)) {
        setSelected(i);
        break;
      }
  }
  private void moveHeadToTail() {
    Pickers head = mDataList.get(0);
    mDataList.remove(0);
    mDataList.add(head);
  }
  private void moveTailToHead() {
    Pickers tail = mDataList.get(mDataList.size() - 1);
    mDataList.remove(mDataList.size() - 1);
    mDataList.add(0, tail);
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    mViewHeight = getMeasuredHeight();
    mViewWidth = getMeasuredWidth();
    // 按照View的高度计算字体大小
    mMaxTextSize = mViewHeight / 8.0f;
    mMinTextSize = mMaxTextSize / 2f;
    isInit = true;
    invalidate();
  }
  private void init() {
    timer = new Timer();
    mDataList = new ArrayList<Pickers>();
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStyle(Style.FILL);
    mPaint.setTextAlign(Align.CENTER);
    mPaint.setColor(getResources().getColor(R.color.white));
  }
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 根据index绘制view
    if (isInit)
      drawData(canvas);
  }
  private void drawData(Canvas canvas) {
    // 先绘制选中的text再往上往下绘制其余的text
    float scale = parabola(mViewHeight / 4.0f, mMoveLen);
    float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
    mPaint.setTextSize(size);
    mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
    // text居中绘制,注意baseline的计算才能达到居中,y值是text中心坐标
    float x = (float) (mViewWidth / 2.0);
    float y = (float) (mViewHeight / 2.0 + mMoveLen);
    FontMetricsInt fmi = mPaint.getFontMetricsInt();
    float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));
    int indexs = mCurrentSelected;
    String textData = mDataList.get(indexs).getShowConetnt();
    canvas.drawText(textData, x, baseline, mPaint);
    // 绘制上方data
    for (int i = 1; (mCurrentSelected - i) >= 0; i++) {
      drawOtherText(canvas, i, -1);
    }
    // 绘制下方data
    for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) {
      drawOtherText(canvas, i, 1);
    }
  }
  /**
   * @param canvas
   * @param position
   *            距离mCurrentSelected的差值
   * @param type
   *            1表示向下绘制,-1表示向上绘制
   */
  private void drawOtherText(Canvas canvas, int position, int type) {
    float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
        * mMoveLen);
    float scale = parabola(mViewHeight / 4.0f, d);
    float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;
    mPaint.setTextSize(size);
    mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
    float y = (float) (mViewHeight / 2.0 + type * d);
    FontMetricsInt fmi = mPaint.getFontMetricsInt();
    float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));
    int indexs = mCurrentSelected + type * position;
    String textData = mDataList.get(indexs).getShowConetnt();
    canvas.drawText(textData, (float) (mViewWidth / 2.0), baseline, mPaint);
  }
  /**
   * 抛物线
   * 
   * @param zero
   *            零点坐标
   * @param x
   *            偏移量
   * @return scale
   */
  private float parabola(float zero, float x) {
    float f = (float) (1 - Math.pow(x / zero, 2));
    return f < 0 ? 0 : f;
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getActionMasked()) {
    case MotionEvent.ACTION_DOWN:
      doDown(event);
      break;
    case MotionEvent.ACTION_MOVE:
      doMove(event);
      break;
    case MotionEvent.ACTION_UP:
      doUp(event);
      break;
    }
    return true;
  }
  private void doDown(MotionEvent event) {
    if (mTask != null) {
      mTask.cancel();
      mTask = null;
    }
    mLastDownY = event.getY();
  }
  private void doMove(MotionEvent event) {
    mMoveLen += (event.getY() - mLastDownY);
    if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2) {
      // 往下滑超过离开距离
      moveTailToHead();
      mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
    } else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2) {
      // 往上滑超过离开距离
      moveHeadToTail();
      mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
    }
    mLastDownY = event.getY();
    invalidate();
  }
  private void doUp(MotionEvent event) {
    // 抬起手后mCurrentSelected的位置由当前位置move到中间选中位置
    if (Math.abs(mMoveLen) < 0.0001) {
      mMoveLen = 0;
      return;
    }
    if (mTask != null) {
      mTask.cancel();
      mTask = null;
    }
    mTask = new MyTimerTask(updateHandler);
    timer.schedule(mTask, 0, 10);
  }
  class MyTimerTask extends TimerTask {
    Handler handler;
    public MyTimerTask(Handler handler) {
      this.handler = handler;
    }
    @Override
    public void run() {
      handler.sendMessage(handler.obtainMessage());
    }
  }
  public interface onSelectListener {
    void onSelect(Pickers pickers);
  }
}


相关文章
|
iOS开发
iOS 多个滚动控件嵌套Demo
iOS 多个滚动控件嵌套Demo
74 0
|
iOS开发
iOS 常用的 上下左右 拉刷新控件
iOS 常用的 上下左右 拉刷新控件
110 0
|
iOS开发
iOS 检测字符串中是否含有字母、大写字母、小写字母
iOS 检测字符串中是否含有字母、大写字母、小写字母
335 0
|
iOS开发
iOS短信验证码控件,自动输入回调两次解决办法
iOS短信验证码控件,自动输入回调两次解决办法
494 0
|
iOS开发
IOS的UITableView控件简单使用
IOS的UITableView控件简单使用
163 0
|
iOS开发
iOS开发 - 写一个刷新的控件(未封装,适合新手学习,查看原理)
iOS开发 - 写一个刷新的控件(未封装,适合新手学习,查看原理)
150 0
iOS开发 - 写一个刷新的控件(未封装,适合新手学习,查看原理)
|
安全 iOS开发
iOS小技能:下拉刷新控件的适配
1. 下拉顶部背景色设置: 往tableView的父控件添加拉伸背景视图 2. present 半屏适配 iOS13 modalPresentationStyle属性默认不是全屏样式`UIModalPresentationFullScreen`,而是半屏样式,需要根据需求手动设置。 present 半屏,会导致列表下拉刷新失效。
211 0
iOS小技能:下拉刷新控件的适配
|
iOS开发
iOS小技能:自动布局实现兄弟控件N等分且宽高比例是1:N(xib 上实现)
本文为 iOS视图约束专题的第三篇:xib上使用自动布局教程
186 0
|
存储 前端开发 程序员
iOS开发:实现点击常用控件弹出地区选择框(万能方法)
在iOS开发中会遇到一些选择选项的需求,而且点击一个控件弹出一个选择框,选择之后展示到前端,然后再把选择的内容传给后台或者做本地存储。这个需求对于大多数开发者来说可以为小儿科,但是作为一个爱记录的程序猿来说相当可贵,所以还是那句话,只分享给有缘人,大牛可以飘过,不喜勿喷请走开。
442 0
iOS开发:实现点击常用控件弹出地区选择框(万能方法)
|
数据可视化 程序员 iOS开发
iOS开发:用XIB拖控件关联时报错:“Could not insert new outlet connection…”解决方法
在iOS开发过程中,尤其是iOS开发初期,会遇到各种各样的错误,有些错误是开发者的不熟悉或者疏忽大意造成的,还有些是无厘头的错误,可以通过重启Xcode或者重启电脑就可解决。
284 0
iOS开发:用XIB拖控件关联时报错:“Could not insert new outlet connection…”解决方法