android 100行代码实现 仿苹果滑动选择器WheelView

效果

android 100行代码实现 仿苹果滑动选择器WheelView_第1张图片

 

源码

public class WheelView extends ListView {

 private List datas = new ArrayList();
 private BaseAdapter adapter;

 public WheelView(Context context, AttributeSet attrs) {
  super(context, attrs);

  for (int i = 0; i < 18; i++) {
   datas.add(i);
  }
  adapter = new BaseAdapter() {
   public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
     convertView = View.inflate(getContext(), R.layout.item_num,
       null);
    }

    int index = position % (datas.size() / 2);
    int data = datas.get(index);

    TextView num = (TextView) convertView.findViewById(R.id.num);
    num.setText(String.valueOf(data));

    num.setTextColor(Color.BLACK);
    if ((getSelectionPosition() % datas.size() + 1) % datas.size() == position
      % datas.size()) {
     num.setTextColor(Color.RED);
    }

    return convertView;
   }

   @Override
   public long getItemId(int position) {
    return position;
   }

   @Override
   public Object getItem(int position) {
    return null;
   }

   @Override
   public int getCount() {
    return Integer.MAX_VALUE;
   }
  };
  setAdapter(adapter);

  setOnScrollListener(new OnScrollListener() {

   public void onScrollStateChanged(AbsListView view, int scrollState) {
    if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
     adapter.notifyDataSetChanged();
     setSelection(9 + getSelectionPosition()
       % (datas.size() / 2));
    }
   }

   public void onScroll(AbsListView view, int firstVisibleItem,
     int visibleItemCount, int totalItemCount) {

   }
  });

  setSelection(datas.size() / 2);
 }

 int getSelectionPosition() {
  int ret = 0;
  if (getChildCount() > 0) {
   int h = getChildAt(0).getMeasuredHeight();
   Rect r = new Rect();
   getChildAt(0).getLocalVisibleRect(r);
   if (r.height() > h / 2) {
    ret = getFirstVisiblePosition();
   } else {
    ret = getFirstVisiblePosition() + 1;
   }
  }
  return ret;
 }

}


你可能感兴趣的:(android)