实训第七周(1)

李晨晨:

本周我主要想实现聊天界面的RecycleView相关内容。

本次主要实现MsgRecyclerView

[java]  view plain  copy
  1. public MsgRecyclerView(Context context) {  
  2.         this(context, null);  
  3.     }  
  4.   
  5.     public MsgRecyclerView(Context context, @Nullable AttributeSet attrs) {  
  6.         this(context, attrs, 0);  
  7.     }  
  8.   
  9.     public MsgRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {  
  10.         super(context, attrs, defStyle);  
  11.         init();  
  12.     }  
  13.   
  14.     private void init() {  
  15.         mLayoutManager = new LinearLayoutManager(getContext());  
  16.         setLayoutManager(mLayoutManager);  
  17.         mHeadView = new MsgHeadView(getContext());  
  18.     }  
  19.   
  20.     public void hideHeadView() {  
  21.         mHeadView.setVisibleHeight(0);  
  22.         isLoading = false;  
  23.     }  
  24.   
  25.     @Override  
  26.     public void setAdapter(Adapter adapter) {  
  27.         mMsgViewAdapter = new MsgViewAdapter(adapter);  
  28.         super.setAdapter(mMsgViewAdapter);  
  29.         adapter.registerAdapterDataObserver(mDataObserver);  
  30.         mDataObserver.onChanged();  
  31.     }  
  32.   
  33.     @Override  
  34.     public Adapter getAdapter() {  
  35.         return mMsgViewAdapter.getOriginalAdapter();  
  36.     }  

因为消息列表有MsgHeadView和普通的RecycleView,所以新写了一个Adapter类,用于包含所有的内容:

[java]  view plain  copy
  1. private class MsgViewAdapter extends Adapter<ViewHolder> {  
  2.   
  3.         private Adapter mAdapter;  
  4.   
  5.         public MsgViewAdapter(Adapter adapter) {  
  6.             this.mAdapter = adapter;  
  7.         }  
  8.   
  9.         public RecyclerView.Adapter getOriginalAdapter() {  
  10.             return this.mAdapter;  
  11.         }  
  12.   
  13.         @Override  
  14.         public int getItemViewType(int position) {  
  15.             if (position == 0) {  
  16.                 return VIEW_TYPE_HEADER;  
  17.             }  
  18.             return mAdapter.getItemViewType(position);  
  19.         }  
  20.   
  21.         @Override  
  22.         public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {  
  23.             if (viewType == VIEW_TYPE_HEADER) {  
  24.                 return new SimpleViewHolder(mHeadView);  
  25.             }  
  26.             return mAdapter.onCreateViewHolder(parent, viewType);  
  27.         }  
  28.   
  29.         @Override  
  30.         public void onBindViewHolder(ViewHolder holder, int position) {  
  31.             if (position == 0) {  
  32.                 return;  
  33.             }  
  34.             mAdapter.onBindViewHolder(holder, position);  
  35.         }  
  36.   
  37.         @Override  
  38.         public int getItemCount() {  
  39.             return mAdapter.getItemCount() + 1;  
  40.         }  
  41.   
  42.         @Override  
  43.         public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {  
  44.             mAdapter.onViewDetachedFromWindow(holder);  
  45.         }  
  46.   
  47.         @Override  
  48.         public void onViewRecycled(RecyclerView.ViewHolder holder) {  
  49.             mAdapter.onViewRecycled(holder);  
  50.         }  
  51.   
  52.         @Override  
  53.         public boolean onFailedToRecycleView(RecyclerView.ViewHolder holder) {  
  54.             return mAdapter.onFailedToRecycleView(holder);  
  55.         }  
  56.   
  57.         @Override  
  58.         public void unregisterAdapterDataObserver(AdapterDataObserver observer) {  
  59.             mAdapter.unregisterAdapterDataObserver(observer);  
  60.         }  
  61.   
  62.         @Override  
  63.         public void registerAdapterDataObserver(AdapterDataObserver observer) {  
  64.             mAdapter.registerAdapterDataObserver(observer);  
  65.         }  
  66.   
  67.         private class SimpleViewHolder extends RecyclerView.ViewHolder {  
  68.             SimpleViewHolder(View itemView) {  
  69.                 super(itemView);  
  70.             }  
  71.         }  
  72.     }  

2.为adapter设置观察者

自定义的DataObserver:

[java]  view plain  copy
  1. private class DataObserver extends RecyclerView.AdapterDataObserver {  
  2.         @Override  
  3.         public void onChanged() {  
  4.             if (mMsgViewAdapter != null) {  
  5.                 mMsgViewAdapter.notifyDataSetChanged();  
  6.             }  
  7.         }  
  8.   
  9.         @Override  
  10.         public void onItemRangeInserted(int positionStart, int itemCount) {  
  11.             mMsgViewAdapter.notifyItemRangeInserted(positionStart, itemCount);  
  12.         }  
  13.   
  14.         @Override  
  15.         public void onItemRangeChanged(int positionStart, int itemCount) {  
  16.             mMsgViewAdapter.notifyItemRangeChanged(positionStart, itemCount);  
  17.         }  
  18.   
  19.         @Override  
  20.         public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {  
  21.             mMsgViewAdapter.notifyItemRangeChanged(positionStart, itemCount, payload);  
  22.         }  
  23.   
  24.         @Override  
  25.         public void onItemRangeRemoved(int positionStart, int itemCount) {  
  26.             mMsgViewAdapter.notifyItemRangeRemoved(positionStart, itemCount);  
  27.         }  
  28.   
  29.         @Override  
  30.         public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {  
  31.             mMsgViewAdapter.notifyItemMoved(fromPosition, toPosition);  
  32.         }  
  33.     }  

3.下拉刷新相关的view显示:

[java]  view plain  copy
  1. @Override  
  2.    public boolean onTouchEvent(MotionEvent e) {  
  3.        switch (e.getAction()) {  
  4.            case MotionEvent.ACTION_DOWN:  
  5.                // 记录手指按下时坐标  
  6.                mLastY = e.getRawY();  
  7.                break;  
  8.            case MotionEvent.ACTION_MOVE:  
  9.                // 计算手指滑动距离,并更新当前 Y 值  
  10.                final float deltaY = e.getRawY() - mLastY;  
  11.                mLastY = e.getRawY();  
  12.                // 若当前处于列表最上方,且headView 当前显示高度小于完整高度2倍,则更新 headView 的显示高度  
  13.                if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0  
  14.                        && (deltaY > 0) && !isLoading  
  15.                        && mHeadView.getVisibleHeight() <= mHeadView.getHeadHeight() * 2) {  
  16.                    mHeadView.setVisibleHeight((int) (deltaY / OFFSET_RADIO + mHeadView.getVisibleHeight()));  
  17.                }  
  18.                break;  
  19.            case MotionEvent.ACTION_UP:  
  20.                mLastY = -1;  
  21.                // 如果 headView 显示高度大于原始高度,则刷新消息列表  
  22.                if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {  
  23.                    if (!isLoading && mHeadView.getVisibleHeight() > mHeadView.getHeadHeight()) {  
  24.                        if (mLoadingListener != null) {  
  25.                            mLoadingListener.loadPreMessage();  
  26.                            isLoading = true;  
  27.                        }  
  28.                        mHeadView.setVisibleHeight(mHeadView.getHeadHeight());  
  29.                    }else {  
  30.                        // 否则,隐藏headView  
  31.                        hideHeadView();  
  32.                    }  
  33.                }  
  34.                break;  
  35.        }  
  36.        return super.onTouchEvent(e);  
  37.    }  
  38.   
  39.    public void setLoadingListener(OnLoadingListener loadingListener) {  
  40.        mLoadingListener = loadingListener;  
  41.    }  
  42.   
  43.    public interface OnLoadingListener {  
  44.        void loadPreMessage();  
  45.    }  



仝心:

这次做了一些关于登陆界面的基本布局的工作,登陆界面的功能的实现(包括注册、填写账号、密码、登陆等)将在接下来的工作中逐步实现。

首先是登陆界面的布局文件,包括背景、分别输入账号和密码的文本框、登陆按键、注册按键、:

[java]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:fitsSystemWindows="true"  
  8.     android:background="@drawable/splash"  
  9.     android:orientation="vertical">  
  10.   
  11.     <!--Android图片圆角类库,一个支持每个图片角不同半径圆角的Android ImageView-->  
  12.     <com.joooonho.SelectableRoundedImageView  
  13.         android:id="@+id/imageView"  
  14.         android:layout_width="80dp"  
  15.         android:layout_height="80dp"  
  16.         app:sriv_left_top_corner_radius="20dp"  
  17.         app:sriv_left_bottom_corner_radius="20dp"  
  18.         app:sriv_right_bottom_corner_radius="20dp"  
  19.         app:sriv_right_top_corner_radius="20dp"  
  20.         android:layout_gravity="center_horizontal"  
  21.         android:layout_marginTop="58dp"  
  22.         android:src="@mipmap/app_logo_white"/>  
  23.   
  24.     <LinearLayout  
  25.         android:layout_width="match_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:layout_marginTop="50dp"  
  28.         android:layout_marginLeft="40dp"  
  29.         android:gravity="center_vertical"  
  30.         android:orientation="horizontal">  
  31.   
  32.         <ImageView  
  33.             android:layout_width="24dp"  
  34.             android:layout_height="24dp"  
  35.             android:src="@mipmap/icon_user_account" />  
  36.   
  37.         <EditText  
  38.             android:id="@+id/et_user_account"  
  39.             android:layout_width="match_parent"  
  40.             android:layout_height="wrap_content"  
  41.             android:layout_marginLeft="16dp"  
  42.             android:background="@null"  
  43.             android:hint="请输入账号"  
  44.             android:digits="@string/digits"  
  45.             android:inputType="textEmailAddress"  
  46.             android:textColor="@android:color/white"  
  47.             android:textColorHint="@color/white_color"  
  48.             android:textSize="16sp" />  
  49.     </LinearLayout>  
  50.   
  51.     <View  
  52.         android:layout_width="match_parent"  
  53.         android:layout_height="0.8dp"  
  54.         android:layout_marginLeft="38dp"  
  55.         android:layout_marginRight="38dp"  
  56.         android:layout_marginTop="7dp"  
  57.         android:background="@color/hint_color" />  
  58.   
  59.     <LinearLayout  
  60.         android:layout_width="match_parent"  
  61.         android:layout_height="wrap_content"  
  62.         android:layout_marginTop="38dp"  
  63.         android:layout_marginLeft="40dp"  
  64.         android:gravity="center_vertical"  
  65.         android:orientation="horizontal">  
  66.   
  67.         <ImageView  
  68.             android:layout_width="24dp"  
  69.             android:layout_height="24dp"  
  70.             android:src="@mipmap/icon_pass_word" />  
  71.   
  72.         <EditText  
  73.             android:id="@+id/et_pass_word"  
  74.             android:layout_width="match_parent"  
  75.             android:layout_height="wrap_content"  
  76.             android:layout_marginLeft="16dp"  
  77.             android:background="@null"  
  78.             android:hint="请输入密码"  
  79.             android:digits="@string/digits"  
  80.             android:inputType="textPassword"  
  81.             android:textColor="@android:color/white"  
  82.             android:textColorHint="@color/white_color"  
  83.             android:textSize="16sp" />  
  84.     </LinearLayout>  
  85.   
  86.     <View  
  87.         android:layout_width="match_parent"  
  88.         android:layout_height="0.8dp"  
  89.         android:layout_marginLeft="38dp"  
  90.         android:layout_marginRight="38dp"  
  91.         android:layout_marginTop="7dp"  
  92.         android:background="@color/hint_color" />  
  93.   
  94.     <TextView  
  95.         android:id="@+id/tv_btn_login"  
  96.         android:layout_width="match_parent"  
  97.         android:layout_height="42dp"  
  98.         android:layout_gravity="center_horizontal"  
  99.         android:layout_marginLeft="38dp"  
  100.         android:layout_marginRight="38dp"  
  101.         android:layout_marginTop="46dp"  
  102.         android:gravity="center"  
  103.         android:background="@drawable/login_nol_bg"  
  104.         android:text="@string/login"  
  105.         android:textColor="#1A8ECB"  
  106.         android:textSize="16sp" />  
  107.   
  108.     <TextView  
  109.         android:id="@+id/tv_btn_register"  
  110.         android:layout_width="wrap_content"  
  111.         android:layout_height="wrap_content"  
  112.         android:layout_gravity="center_horizontal"  
  113.         android:layout_marginTop="4dp"  
  114.         android:gravity="center"  
  115.         android:paddingTop="20dp"  
  116.         android:text="@string/register_tip"  
  117.         android:textColor="@color/white_color"  
  118.         android:textSize="14sp"/>  
  119.   
  120.     <View  
  121.         android:layout_width="120dp"  
  122.         android:layout_height="0.8dp"  
  123.         android:layout_gravity="center_horizontal"  
  124.         android:background="@color/white_color" />  
  125.   
  126.     <RelativeLayout  
  127.         android:layout_width="match_parent"  
  128.         android:layout_height="match_parent"  
  129.         android:layout_marginTop="6dp">  
  130.   
  131.         <TextView  
  132.             android:layout_width="wrap_content"  
  133.             android:layout_height="wrap_content"  
  134.             android:layout_alignParentBottom="true"  
  135.             android:layout_centerHorizontal="true"  
  136.             android:layout_marginBottom="6dp"  
  137.             android:textColor="@color/app_blue_color"  
  138.             android:text="@string/app_version"/>  
  139.     </RelativeLayout>  
  140.   
  141. </LinearLayout>  

聊天通信通过借助网易云通信来实现,在gradle中添加一下代码请求这些功能

[java]  view plain  copy
  1.     // 基础功能 (必需)  
  2.     compile 'com.netease.nimlib:basesdk:3.3.0'  
  3.     // 音视频需要  
  4.     compile 'com.netease.nimlib:avchat:3.3.0'  
  5.     // 全文检索服务需要  
  6.     compile 'com.netease.nimlib:lucene:3.3.0'  

导入在文件中导入相关的库

[java]  view plain  copy
  1. import com.netease.nimlib.sdk.AbortableFuture;  
  2. import com.netease.nimlib.sdk.NIMClient;  
  3. import com.netease.nimlib.sdk.RequestCallback;  
  4. import com.netease.nimlib.sdk.auth.AuthService;  
  5. import com.netease.nimlib.sdk.auth.LoginInfo;  

分配一个数组用来存储各种需要申请的权限(sd卡写的权限、相机权限、读取手机状态数据的权限、录音权限、获取粗略位置(基站服务信号)和精确位置(GPS)的权限)

[java]  view plain  copy
  1. private final String[] BASIC_PERMISSIONS = new String[]{  
  2.             Manifest.permission.WRITE_EXTERNAL_STORAGE,  
  3.             Manifest.permission.CAMERA,  
  4.             Manifest.permission.READ_PHONE_STATE,  
  5.             Manifest.permission.RECORD_AUDIO,  
  6.             Manifest.permission.ACCESS_COARSE_LOCATION,  
  7.             Manifest.permission.ACCESS_FINE_LOCATION  
  8.     };  

检查、申请权限的方法

[java]  view plain  copy
  1. private void initPermission(){  
  2.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){  
  3.             boolean has = PermissionUtils.checkPermissions(this, BASIC_PERMISSIONS);  
  4.             if (!has){  
  5.                 PermissionUtils.requestPermissions(this,PERMISSION_REQUEST_CODE,BASIC_PERMISSIONS);  
  6.             }  
  7.         }  

跳转到权限设置页面返回后再次检查

[java]  view plain  copy
  1. protected void onRestart() {  
  2.         super.onRestart();  
  3.         initPermission();  
  4.     }  

权限授予结果回调

[java]  view plain  copy
  1. @Override  
  2.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,  
  3.                                            @NonNull int[] grantResults) {  
  4.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);  
  5.         if (requestCode == PERMISSION_REQUEST_CODE){  
  6.             PermissionUtils.dealPermissionResult(LoginActivity.this, permissions, grantResults,  
  7.                     new PermissionUtils.RequestPermissionCallBack() {  
  8.                         @Override  
  9.                         public void onGrant(String... permissions) {  
  10.   
  11.                         }  
  12.   
  13.                         @Override  
  14.                         public void onDenied(String... permissions) {  
  15.   
  16.                         }  
  17.   
  18.                         @Override  
  19.                         public void onDeniedAndNeverAsk(String... permissions) {  
  20.   
  21.                         }  
  22.                     });  
  23.         }  
  24.     }  

Activity的OnCreate方法:

[java]  view plain  copy
  1. @Override  
  2.     protected void onCreate(@Nullable Bundle savedInstanceState) {  
  3.         super.onCreate(savedInstanceState);  
  4.         setContentView(R.layout.activity_login);  
  5.         ButterKnife.bind(this);  
  6.         mEtPassWord.setOnTouchListener(new MyTouchListener());  
  7.         initPermission();  
  8.     }  

因为日后需要保存登陆信息,所以这里自定义一个SharedPreferencesUtil通过SharedPreferences提供的java常规的Long、Int、String等类型数据的保存接口来存储登陆信息

[java]  view plain  copy
  1. public static void setIntSharedPreferences(Context context, String name, String key, int value) {  
  2.         SharedPreferences sharedPreferences = context.getSharedPreferences(name, Activity.MODE_PRIVATE);  
  3.         SharedPreferences.Editor editor = sharedPreferences.edit();  
  4.         editor.putInt(key, value);  
  5.         editor.commit();  
  6.     }  
  7.   
  8.     public static void setStringSharedPreferences(Context context, String name, String key, String value) {  
  9.         SharedPreferences sharedPreferences = context.getSharedPreferences(name, Activity.MODE_PRIVATE);  
  10.         SharedPreferences.Editor editor = sharedPreferences.edit();  
  11.         if (sharedPreferences.contains(key)) {  
  12.             editor.remove(key);  
  13.             editor.commit();  
  14.         }  
  15.         editor.putString(key, value);  
  16.         editor.commit();  
  17.     }  
  18.   
  19.     public static int getIntSharedPreferences(Context context, String name, String key) {  
  20.         SharedPreferences sharedPreferences = context.getSharedPreferences(name, Activity.MODE_PRIVATE);  
  21.         int value = sharedPreferences.getInt(key, 0);  
  22.         return value;  
  23.     }  
  24.     public static String getStringSharedPreferences(Context context, String name, String key) {  
  25.         SharedPreferences sharedPreferences = context.getSharedPreferences(name, Activity.MODE_PRIVATE);  
  26.         String value = sharedPreferences.getString(key, "");  
  27.         return value;  
  28.     }  

在日后实现登陆及其它的一些功能时会用到这个类中的方法。



张静:

本周开始写WheelView——滚轮控件

我想要实现的设置生日日期,地区的方式都是用户可在可选时间,地区列表中滚动选择

所以需用到滚轮,先写滚轮控件

(1)初始化,获取设置的属性

attr.xml

[java]  view plain  copy
  1. <declare-styleable name="WheelView">  
  2.         <attr name="unitHeight" format="dimension" />  
  3.         <attr name="itemNumber" format="integer"/>  
  4.   
  5.         <attr name="normalTextColor" format="color" />  
  6.         <attr name="normalTextSize" format="dimension" />  
  7.         <attr name="selectedTextColor" format="color" />  
  8.         <attr name="selectedTextSize" format="dimension" />  
  9.   
  10.         <attr name="lineColor" format="color" />  
  11.         <attr name="lineHeight" format="dimension" />  
  12.   
  13.         <attr name="maskHeight" format="dimension"/>  
  14.         <attr name="noEmpty" format="boolean"/>  
  15.         <attr name="isEnable" format="boolean"/>  
  16.     </declare-styleable>  

[java]  view plain  copy
  1. private void init(Context context, AttributeSet attrs) {  
  2.   
  3.     TypedArray attribute = context.obtainStyledAttributes(attrs, R.styleable.WheelView);  
  4.     unitHeight = (int) attribute.getDimension(R.styleable.WheelView_unitHeight, unitHeight);//单元格高度  
  5.     itemNumber = attribute.getInt(R.styleable.WheelView_itemNumber, itemNumber);//显示多少个内容  
  6.   
  7.     normalFont = attribute.getDimension(R.styleable.WheelView_normalTextSize, normalFont);//默认字体  
  8.     selectedFont = attribute.getDimension(R.styleable.WheelView_selectedTextSize, selectedFont);//选中时字体  
  9.     normalColor = attribute.getColor(R.styleable.WheelView_normalTextColor, normalColor);//默认字体颜色  
  10.     selectedColor = attribute.getColor(R.styleable.WheelView_selectedTextColor, selectedColor);//选中时候的字体颜色  
  11.   
  12.     lineColor = attribute.getColor(R.styleable.WheelView_lineColor, lineColor);//线的默认颜色  
  13.     lineHeight = attribute.getDimension(R.styleable.WheelView_lineHeight, lineHeight);//线的默认宽度  
  14.   
  15.     maskHeight = attribute.getDimension(R.styleable.WheelView_maskHeight, maskHeight);//蒙版高度  
  16.     noEmpty = attribute.getBoolean(R.styleable.WheelView_noEmpty, true);//是否允许选  
  17.     isEnable = attribute.getBoolean(R.styleable.WheelView_isEnable, true);//是否可用  
  18.   
  19.     attribute.recycle();  
  20.   
  21.     controlHeight = itemNumber * unitHeight;  
  22. }  

(2)初始化数据

[java]  view plain  copy
  1. private void initData() {  
  2.     isClearing = true;  
  3.     itemList.clear();  
  4.     for (int i = 0; i < dataList.size(); i++) {  
  5.         ItemObject itemObject = new ItemObject();  
  6.         itemObject.id = i;  
  7.         itemObject.itemText = dataList.get(i);  
  8.         itemObject.x = 0;  
  9.         itemObject.y = i * unitHeight;  
  10.         itemList.add(itemObject);  
  11.     }  
  12.     isClearing = false;  
  13. }  

其中,ItemObject(单条内容)

[java]  view plain  copy
  1. private class ItemObject {  
  2.     /**id*/  
  3.     public int id = 0;  
  4.     /*** 内容*/  
  5.     public String itemText = "";  
  6.     /*** x坐标*/  
  7.     public int x = 0;  
  8.     /*** y坐标*/  
  9.     public int y = 0;  
  10.     /*** 移动距离*/  
  11.     public int move = 0;  
  12.     /*** 字体画笔*/  
  13.     private TextPaint textPaint;  
  14.     /*** 字体范围矩形*/  
  15.     private Rect textRect;  
  16.   
  17.     public ItemObject() {  
  18.         super();  
  19.     }  
  20.   
  21.     /** 
  22.      * 绘制自身 
  23.      * 
  24.      * @param canvas         画板 
  25.      * @param containerWidth 容器宽度 
  26.      */  
  27.     public void drawSelf(Canvas canvas, int containerWidth) {  
  28.   
  29.         if (textPaint == null) {  
  30.             textPaint = new TextPaint();  
  31.             textPaint.setAntiAlias(true);//防止锯齿  
  32.         }  
  33.   
  34.         if (textRect == null)  
  35.             textRect = new Rect();  
  36.   
  37.         // 判断是否被选择  
  38.         if (isSelected()) {  
  39.             textPaint.setColor(selectedColor);  
  40.             // 获取距离标准位置的距离  
  41.             float moveToSelect = moveToSelected();  
  42.             moveToSelect = moveToSelect > 0 ? moveToSelect : moveToSelect * (-1);  
  43.             // 计算当前字体大小  
  44.             float textSize = normalFont  
  45.                     + ((selectedFont - normalFont) * (1.0f - moveToSelect / (float) unitHeight));  
  46.             textPaint.setTextSize(textSize);  
  47.         } else {  
  48.             textPaint.setColor(normalColor);  
  49.             textPaint.setTextSize(normalFont);  
  50.         }  
  51.   
  52.         // 返回包围整个字符串的最小的一个Rect区域  
  53.         itemText = (String) TextUtils.ellipsize(itemText, textPaint, containerWidth, TextUtils.TruncateAt.END);  
  54.         textPaint.getTextBounds(itemText, 0, itemText.length(), textRect);  
  55.         // 判断是否可视  
  56.         if (!isInView())  
  57.             return;  
  58.   
  59.         // 绘制内容  
  60.         canvas.drawText(itemText, x + controlWidth / 2 - textRect.width() / 2,  
  61.                 y + move + unitHeight / 2 + textRect.height() / 2, textPaint);  
  62.   
  63.     }  
  64.   
  65.     /*** 是否在可视界面内*/  
  66.     public boolean isInView() {  
  67.         if (y + move > controlHeight || (y + move + unitHeight / 2 + textRect.height() / 2) < 0)  
  68.             return false;  
  69.         return true;  
  70.     }  
  71.   
  72.     /*** 移动距离*/  
  73.     public void move(int _move) {  
  74.         this.move = _move;  
  75.     }  
  76.   
  77.     /*** 设置新的坐标*/  
  78.     public void newY(int _move) {  
  79.         this.move = 0;  
  80.         this.y = y + _move;  
  81.     }  
  82.   
  83.     /*** 判断是否在选择区域内*/  
  84.     public boolean isSelected() {  
  85.         if ((y + move) >= controlHeight / 2 - unitHeight / 2 + lineHeight  
  86.                 && (y + move) <= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  87.             return true;  
  88.         }  
  89.         if ((y + move + unitHeight) >= controlHeight / 2 - unitHeight / 2 + lineHeight  
  90.                 && (y + move + unitHeight) <= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  91.             return true;  
  92.         }  
  93.         if ((y + move) <= controlHeight / 2 - unitHeight / 2 + lineHeight  
  94.                 && (y + move + unitHeight) >= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  95.             return true;  
  96.         }  
  97.         return false;  
  98.     }  
  99.   
  100.     /*** 获取移动到标准位置需要的距离*/  
  101.     public float moveToSelected() {  
  102.         return (controlHeight / 2 - unitHeight / 2) - (y + move);  
  103.     }  
  104. }  

(3)绘制线条

[java]  view plain  copy
  1. private void drawLine(Canvas canvas) {  
  2.   
  3.     if (linePaint == null) {  
  4.         linePaint = new Paint();  
  5.         linePaint.setColor(lineColor);  
  6.         linePaint.setAntiAlias(true);  
  7.         linePaint.setStrokeWidth(lineHeight);//设置画笔宽度  
  8.     }  
  9.   
  10.     canvas.drawLine(0, controlHeight / 2 - unitHeight / 2 + lineHeight,  
  11.             controlWidth, controlHeight / 2 - unitHeight / 2 + lineHeight, linePaint);  
  12.     canvas.drawLine(0, controlHeight / 2 + unitHeight / 2 - lineHeight,  
  13.             controlWidth, controlHeight / 2 + unitHeight / 2 - lineHeight, linePaint);  
  14. }  

(4)绘制列表

[java]  view plain  copy
  1. private synchronized void drawList(Canvas canvas) {  
  2.     if (isClearing)  
  3.         return;  
  4.     try {  
  5.         for (ItemObject itemObject : itemList) {  
  6.             itemObject.drawSelf(canvas, getMeasuredWidth());  
  7.         }  
  8.     } catch (Exception e) {  
  9.     }  
  10. }  

(5)绘制遮盖板

[java]  view plain  copy
  1. private void drawMask(Canvas canvas) {  
  2.     LinearGradient lg = new LinearGradient(000, maskHeight, 0x00f2f2f2,  
  3.             0x00f2f2f2, TileMode.MIRROR);  
  4.     Paint paint = new Paint();  
  5.     paint.setShader(lg);  
  6.     canvas.drawRect(00, controlWidth, maskHeight, paint);  
  7.   
  8.     LinearGradient lg2 = new LinearGradient(0, controlHeight - maskHeight,  
  9.             0, controlHeight, 0x00f2f2f20x00f2f2f2, TileMode.MIRROR);  
  10.     Paint paint2 = new Paint();  
  11.     paint2.setShader(lg2);  
  12.     canvas.drawRect(0, controlHeight - maskHeight, controlWidth,  
  13.             controlHeight, paint2);  
  14. }  

(6) 触摸事件

获取纵坐标(设置时间,滚轮是纵向移动)

获得的触摸动作为:

a. ACTION_DOWN(按下)

    设置为正在滑动中, 获取当下纵坐标,以及当时系统时间

b. ACTION_MOVE(移动中)

    刷新移动的距离,设置滑动监听

c. ACTION_UP(抬起时)

    计算出这段时间移动的距离

    若滑动时间小于预先设定的短促移动时间并且滑动距离大于预先设定的短促移动距离,则继续移动一段距离

    否则,移动到指定位置,停止移动(actionUp)

[java]  view plain  copy
  1. @Override  
  2. public boolean onTouchEvent(MotionEvent event) {  
  3.     if (!isEnable)  
  4.         return true;  
  5.     int y = (int) event.getY();  
  6.     switch (event.getAction()) {  
  7.         case MotionEvent.ACTION_DOWN:  
  8.             isScrolling = true;  
  9.             downY = (int) event.getY();  
  10.             downTime = System.currentTimeMillis();  
  11.             break;  
  12.         case MotionEvent.ACTION_MOVE:  
  13.             actionMove(y - downY);  
  14.             onSelectListener();  
  15.             break;  
  16.         case MotionEvent.ACTION_UP:  
  17.             int move = Math.abs(y - downY);  
  18.             // 判断这段时间移动的距离  
  19.             if (System.currentTimeMillis() - downTime < goonTime && move > goonDistance) {  
  20.                 goonMove(y - downY);  
  21.             } else {  
  22.                 actionUp(y - downY);  
  23.                 noEmpty();  
  24.                 isScrolling = false;  
  25.             }  
  26.             break;  
  27.         default:  
  28.             break;  
  29.     }  
  30.     return true;  
  31. }  

(7)继续移动一段距离

[java]  view plain  copy
  1. private synchronized void goonMove(final int move) {  
  2.     new Thread(new Runnable() {  
  3.   
  4.         @Override  
  5.         public void run() {  
  6.             int distance = 0;  
  7.             while (distance < unitHeight * MOVE_NUMBER) {  
  8.                 try {  
  9.                     Thread.sleep(5);  
  10.                 } catch (InterruptedException e) {  
  11.                     e.printStackTrace();  
  12.                 }  
  13.                 actionThreadMove(move > 0 ? distance : distance * (-1));  
  14.                 distance += 10;  
  15.   
  16.             }  
  17.             actionUp(move > 0 ? distance - 10 : distance * (-1) + 10);  
  18.             noEmpty();  
  19.         }  
  20.     }).start();  
  21. }  

(8)不能为空,必须有选择

[java]  view plain  copy
  1. private void noEmpty() {  
  2.     if (!noEmpty)  
  3.         return;  
  4.     for (ItemObject item : itemList) {  
  5.         if (item.isSelected())  
  6.             return;  
  7.     }  
  8.     int move = (int) itemList.get(0).moveToSelected();  
  9.     if (move < 0) {  
  10.         defaultMove(move);  
  11.     } else {  
  12.         defaultMove((int) itemList.get(itemList.size() - 1)  
  13.                 .moveToSelected());  
  14.     }  
  15.     for (ItemObject item : itemList) {  
  16.         if (item.isSelected()) {  
  17.             if (onSelectListener != null)  
  18.                 onSelectListener.endSelect(item.id, item.itemText);  
  19.             break;  
  20.         }  
  21.     }  
  22. }  

(9)移动的时候,即触摸事件中,触摸动作为ACTION_MOVE时所作处理

移动触摸时滑动的距离,刷新控件

[java]  view plain  copy
  1. private void actionMove(int move) {  
  2.     for (ItemObject item : itemList) {  
  3.         item.move(move);  
  4.     }  
  5.     invalidate();  
  6. }  

(10)移动,线程中调用

向handler发送刷新信息,移动

[java]  view plain  copy
  1. private void actionThreadMove(int move) {  
  2.     for (ItemObject item : itemList) {  
  3.         item.move(move);  
  4.     }  
  5.     Message rMessage = new Message();  
  6.     rMessage.what = REFRESH_VIEW;  
  7.     handler.sendMessage(rMessage);  
  8. }  

(11)松开的时候

当向上滑动和向下滑动时,分别获取所需移动的距离,监听器结束选择

缓慢移动之前所获得的所需移动距离

通知刷新

[java]  view plain  copy
  1. private void actionUp(int move) {  
  2.     int newMove = 0;  
  3.     if (move > 0) {  
  4.         for (int i = 0; i < itemList.size(); i++) {  
  5.             if (itemList.get(i).isSelected()) {  
  6.                 newMove = (int) itemList.get(i).moveToSelected();  
  7.                 if (onSelectListener != null)  
  8.                     onSelectListener.endSelect(itemList.get(i).id,  
  9.                             itemList.get(i).itemText);  
  10.                 break;  
  11.             }  
  12.         }  
  13.     } else {  
  14.         for (int i = itemList.size() - 1; i >= 0; i--) {  
  15.             if (itemList.get(i).isSelected()) {  
  16.                 newMove = (int) itemList.get(i).moveToSelected();  
  17.                 if (onSelectListener != null)  
  18.                     onSelectListener.endSelect(itemList.get(i).id,  
  19.                             itemList.get(i).itemText);  
  20.                 break;  
  21.             }  
  22.         }  
  23.     }  
  24.     for (ItemObject item : itemList) {  
  25.         item.newY(move + 0);  
  26.     }  
  27.     slowMove(newMove);  
  28.     Message rMessage = new Message();  
  29.     rMessage.what = REFRESH_VIEW;  
  30.     handler.sendMessage(rMessage);  
  31.   
  32. }  

(12)缓慢移动

先判断是向上滑动还是向下滑动的(移动距离取绝对值),设置移动的速度(1)

当还需继续移动时,每移动一格,重设每一项纵坐标,通知刷新,线程睡眠2ms, 移动距离减一,直到已移动完所需距离

每一项结束监听

[java]  view plain  copy
  1. private synchronized void slowMove(final int move) {  
  2.     new Thread(new Runnable() {  
  3.   
  4.         @Override  
  5.         public void run() {  
  6.             // 判断正负  
  7.             int m = move > 0 ? move : move * (-1);  
  8.             int i = move > 0 ? 1 : (-1);  
  9.             // 移动速度  
  10.             int speed = 1;  
  11.             while (true) {  
  12.                 m = m - speed;  
  13.                 if (m <= 0) {  
  14.                     for (ItemObject item : itemList) {  
  15.                         item.newY(m * i);  
  16.                     }  
  17.                     Message rMessage = new Message();  
  18.                     rMessage.what = REFRESH_VIEW;  
  19.                     handler.sendMessage(rMessage);  
  20.                     try {  
  21.                         Thread.sleep(2);  
  22.                     } catch (InterruptedException e) {  
  23.                         e.printStackTrace();  
  24.                     }  
  25.                     break;  
  26.                 }  
  27.                 for (ItemObject item : itemList) {  
  28.                     item.newY(speed * i);  
  29.                 }  
  30.                 Message rMessage = new Message();  
  31.                 rMessage.what = REFRESH_VIEW;  
  32.                 handler.sendMessage(rMessage);  
  33.                 try {  
  34.                     Thread.sleep(2);  
  35.                 } catch (InterruptedException e) {  
  36.                     e.printStackTrace();  
  37.                 }  
  38.             }  
  39.             for (ItemObject item : itemList) {  
  40.                 if (item.isSelected()) {  
  41.                     if (onSelectListener != null)  
  42.                         onSelectListener.endSelect(item.id, item.itemText);  
  43.                     break;  
  44.                 }  
  45.             }  
  46.   
  47.         }  
  48.     }).start();  
  49. }  

(13)滑动监听

[java]  view plain  copy
  1. private void onSelectListener() {  
  2.     if (onSelectListener == null)  
  3.         return;  
  4.     for (ItemObject item : itemList) {  
  5.         if (item.isSelected()) {  
  6.             onSelectListener.selecting(item.id, item.itemText);  
  7.         }  
  8.     }  
  9. }  

(14)选择监听

[java]  view plain  copy
  1.     public interface OnSelectListener {  
  2.         /*** 结束选择*/  
  3.         void endSelect(int id, String text);  
  4.         /*** 选中的内容*/  
  5.         void selecting(int id, String text);  
  6.   
  7.     }  
  8. }  



附上完整WheelView.java

[java]  view plain  copy
  1. package com.ezreal.ezchat.timeselectview;  
  2.   
  3. import android.annotation.SuppressLint;  
  4. import android.content.Context;  
  5. import android.content.res.TypedArray;  
  6. import android.graphics.Canvas;  
  7. import android.graphics.LinearGradient;  
  8. import android.graphics.Paint;  
  9. import android.graphics.Rect;  
  10. import android.graphics.Shader.TileMode;  
  11. import android.os.Handler;  
  12. import android.os.Message;  
  13. import android.text.TextPaint;  
  14. import android.text.TextUtils;  
  15. import android.util.AttributeSet;  
  16. import android.view.MotionEvent;  
  17. import android.view.View;  
  18.   
  19. import com.ezreal.ezchat.R;  
  20.   
  21. import java.util.ArrayList;  
  22.   
  23. /** 
  24.  * Created by 张静 
  25.  */  
  26.   
  27. /*** WheelView滚轮*/  
  28. public class WheelView extends View {  
  29.     /*** 控件宽度*/  
  30.     private float controlWidth;  
  31.     /*** 控件高度*/  
  32.     private float controlHeight;  
  33.     /*** 是否滑动中*/  
  34.     private boolean isScrolling = false;  
  35.     /*** 选择的内容*/  
  36.     private ArrayList<ItemObject> itemList = new ArrayList<>();  
  37.     /*** 设置数据*/  
  38.     private ArrayList<String> dataList = new ArrayList<>();  
  39.     /*** 按下的坐标*/  
  40.     private int downY;  
  41.     /*** 按下的时间*/  
  42.     private long downTime = 0;  
  43.     /*** 短促移动*/  
  44.     private long goonTime = 200;  
  45.     /*** 短促移动距离*/  
  46.     private int goonDistance = 100;  
  47.     /*** 画线画笔*/  
  48.     private Paint linePaint;  
  49.     /*** 线的默认颜色*/  
  50.     private int lineColor = 0xff000000;  
  51.     /*** 线的默认宽度*/  
  52.     private float lineHeight = 2f;  
  53.     /*** 默认字体*/  
  54.     private float normalFont = 14.0f;  
  55.     /*** 选中的时候字体*/  
  56.     private float selectedFont = 22.0f;  
  57.     /*** 单元格高度*/  
  58.     private int unitHeight = 50;  
  59.     /*** 显示多少个内容*/  
  60.     private int itemNumber = 7;  
  61.     /*** 默认字体颜色*/  
  62.     private int normalColor = 0xff000000;  
  63.     /*** 选中时候的字体颜色*/  
  64.     private int selectedColor = 0xffff0000;  
  65.     /*** 蒙板高度*/  
  66.     private float maskHeight = 48.0f;  
  67.     /*** 选择监听*/  
  68.     private OnSelectListener onSelectListener;  
  69.     /*** 是否可用*/  
  70.     private boolean isEnable = true;  
  71.     /*** 刷新界面*/  
  72.     private static final int REFRESH_VIEW = 0x001;  
  73.     /*** 移动距离*/  
  74.     private static final int MOVE_NUMBER = 5;  
  75.     /*** 是否允许选*/  
  76.     private boolean noEmpty = true;  
  77.     /**正在修改数据,避免ConcurrentModificationException异常*/  
  78.     private boolean isClearing = false;  
  79.   
  80.     public WheelView(Context context, AttributeSet attrs, int defStyle) {  
  81.         super(context, attrs, defStyle);  
  82.         init(context, attrs);  
  83.         initData();  
  84.     }  
  85.   
  86.     public WheelView(Context context, AttributeSet attrs) {  
  87.         super(context, attrs);  
  88.         init(context, attrs);  
  89.         initData();  
  90.     }  
  91.   
  92.     public WheelView(Context context) {  
  93.         super(context);  
  94.         initData();  
  95.     }  
  96.   
  97.     /*** 初始化,获取设置的属性*/  
  98.     private void init(Context context, AttributeSet attrs) {  
  99.   
  100.         TypedArray attribute = context.obtainStyledAttributes(attrs, R.styleable.WheelView);  
  101.         unitHeight = (int) attribute.getDimension(R.styleable.WheelView_unitHeight, unitHeight);  
  102.         itemNumber = attribute.getInt(R.styleable.WheelView_itemNumber, itemNumber);  
  103.   
  104.         normalFont = attribute.getDimension(R.styleable.WheelView_normalTextSize, normalFont);  
  105.         selectedFont = attribute.getDimension(R.styleable.WheelView_selectedTextSize, selectedFont);  
  106.         normalColor = attribute.getColor(R.styleable.WheelView_normalTextColor, normalColor);  
  107.         selectedColor = attribute.getColor(R.styleable.WheelView_selectedTextColor, selectedColor);  
  108.   
  109.         lineColor = attribute.getColor(R.styleable.WheelView_lineColor, lineColor);  
  110.         lineHeight = attribute.getDimension(R.styleable.WheelView_lineHeight, lineHeight);  
  111.   
  112.         maskHeight = attribute.getDimension(R.styleable.WheelView_maskHeight, maskHeight);  
  113.         noEmpty = attribute.getBoolean(R.styleable.WheelView_noEmpty, true);  
  114.         isEnable = attribute.getBoolean(R.styleable.WheelView_isEnable, true);  
  115.   
  116.         attribute.recycle();  
  117.   
  118.         controlHeight = itemNumber * unitHeight;  
  119.     }  
  120.   
  121.     /*** 初始化数据*/  
  122.     private void initData() {  
  123.         isClearing = true;  
  124.         itemList.clear();  
  125.         for (int i = 0; i < dataList.size(); i++) {  
  126.             ItemObject itemObject = new ItemObject();  
  127.             itemObject.id = i;  
  128.             itemObject.itemText = dataList.get(i);  
  129.             itemObject.x = 0;  
  130.             itemObject.y = i * unitHeight;  
  131.             itemList.add(itemObject);  
  132.         }  
  133.         isClearing = false;  
  134.     }  
  135.   
  136.     @Override  
  137.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  138.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  139.         controlWidth = getMeasuredWidth();  
  140.         if (controlWidth != 0) {  
  141.             setMeasuredDimension(getMeasuredWidth(), itemNumber * unitHeight);  
  142.         }  
  143.     }  
  144.   
  145.     @Override  
  146.     protected void onDraw(Canvas canvas) {  
  147.         super.onDraw(canvas);  
  148.   
  149.         drawLine(canvas);  
  150.         drawList(canvas);  
  151.         drawMask(canvas);  
  152.     }  
  153.   
  154.     /*** 绘制线条*/  
  155.     private void drawLine(Canvas canvas) {  
  156.   
  157.         if (linePaint == null) {  
  158.             linePaint = new Paint();  
  159.             linePaint.setColor(lineColor);  
  160.             linePaint.setAntiAlias(true);  
  161.             linePaint.setStrokeWidth(lineHeight);  
  162.         }  
  163.   
  164.         canvas.drawLine(0, controlHeight / 2 - unitHeight / 2 + lineHeight,  
  165.                 controlWidth, controlHeight / 2 - unitHeight / 2 + lineHeight, linePaint);  
  166.         canvas.drawLine(0, controlHeight / 2 + unitHeight / 2 - lineHeight,  
  167.                 controlWidth, controlHeight / 2 + unitHeight / 2 - lineHeight, linePaint);  
  168.     }  
  169.   
  170.     private synchronized void drawList(Canvas canvas) {  
  171.         if (isClearing)  
  172.             return;  
  173.         try {  
  174.             for (ItemObject itemObject : itemList) {  
  175.                 itemObject.drawSelf(canvas, getMeasuredWidth());  
  176.             }  
  177.         } catch (Exception e) {  
  178.         }  
  179.     }  
  180.   
  181.     /*** 绘制遮盖板*/  
  182.     private void drawMask(Canvas canvas) {  
  183.         LinearGradient lg = new LinearGradient(000, maskHeight, 0x00f2f2f2,  
  184.                 0x00f2f2f2, TileMode.MIRROR);  
  185.         Paint paint = new Paint();  
  186.         paint.setShader(lg);  
  187.         canvas.drawRect(00, controlWidth, maskHeight, paint);  
  188.   
  189.         LinearGradient lg2 = new LinearGradient(0, controlHeight - maskHeight,  
  190.                 0, controlHeight, 0x00f2f2f20x00f2f2f2, TileMode.MIRROR);  
  191.         Paint paint2 = new Paint();  
  192.         paint2.setShader(lg2);  
  193.         canvas.drawRect(0, controlHeight - maskHeight, controlWidth,  
  194.                 controlHeight, paint2);  
  195.     }  
  196.   
  197.     @Override  
  198.     public boolean onTouchEvent(MotionEvent event) {  
  199.         if (!isEnable)  
  200.             return true;  
  201.         int y = (int) event.getY();  
  202.         switch (event.getAction()) {  
  203.             case MotionEvent.ACTION_DOWN:  
  204.                 isScrolling = true;  
  205.                 downY = (int) event.getY();  
  206.                 downTime = System.currentTimeMillis();  
  207.                 break;  
  208.             case MotionEvent.ACTION_MOVE:  
  209.                 actionMove(y - downY);  
  210.                 onSelectListener();  
  211.                 break;  
  212.             case MotionEvent.ACTION_UP:  
  213.                 int move = Math.abs(y - downY);  
  214.                 // 判断这段时间移动的距离  
  215.                 if (System.currentTimeMillis() - downTime < goonTime && move > goonDistance) {  
  216.                     goonMove(y - downY);  
  217.                 } else {  
  218.                     actionUp(y - downY);  
  219.                     noEmpty();  
  220.                     isScrolling = false;  
  221.                 }  
  222.                 break;  
  223.             default:  
  224.                 break;  
  225.         }  
  226.         return true;  
  227.     }  
  228.   
  229.     /*** 继续移动一定距离*/  
  230.     private synchronized void goonMove(final int move) {  
  231.         new Thread(new Runnable() {  
  232.   
  233.             @Override  
  234.             public void run() {  
  235.                 int distance = 0;  
  236.                 while (distance < unitHeight * MOVE_NUMBER) {  
  237.                     try {  
  238.                         Thread.sleep(5);  
  239.                     } catch (InterruptedException e) {  
  240.                         e.printStackTrace();  
  241.                     }  
  242.                     actionThreadMove(move > 0 ? distance : distance * (-1));  
  243.                     distance += 10;  
  244.   
  245.                 }  
  246.                 actionUp(move > 0 ? distance - 10 : distance * (-1) + 10);  
  247.                 noEmpty();  
  248.             }  
  249.         }).start();  
  250.     }  
  251.   
  252.     /*** 不能为空,必须有选项*/  
  253.     private void noEmpty() {  
  254.         if (!noEmpty)  
  255.             return;  
  256.         for (ItemObject item : itemList) {  
  257.             if (item.isSelected())  
  258.                 return;  
  259.         }  
  260.         int move = (int) itemList.get(0).moveToSelected();  
  261.         if (move < 0) {  
  262.             defaultMove(move);  
  263.         } else {  
  264.             defaultMove((int) itemList.get(itemList.size() - 1)  
  265.                     .moveToSelected());  
  266.         }  
  267.         for (ItemObject item : itemList) {  
  268.             if (item.isSelected()) {  
  269.                 if (onSelectListener != null)  
  270.                     onSelectListener.endSelect(item.id, item.itemText);  
  271.                 break;  
  272.             }  
  273.         }  
  274.     }  
  275.   
  276.     /*** 移动的时候*/  
  277.     private void actionMove(int move) {  
  278.         for (ItemObject item : itemList) {  
  279.             item.move(move);  
  280.         }  
  281.         invalidate();  
  282.     }  
  283.   
  284.     /*** 移动,线程中调用*/  
  285.     private void actionThreadMove(int move) {  
  286.         for (ItemObject item : itemList) {  
  287.             item.move(move);  
  288.         }  
  289.         Message rMessage = new Message();  
  290.         rMessage.what = REFRESH_VIEW;  
  291.         handler.sendMessage(rMessage);  
  292.     }  
  293.   
  294.     /*** 松开的时候*/  
  295.     private void actionUp(int move) {  
  296.         int newMove = 0;  
  297.         if (move > 0) {  
  298.             for (int i = 0; i < itemList.size(); i++) {  
  299.                 if (itemList.get(i).isSelected()) {  
  300.                     newMove = (int) itemList.get(i).moveToSelected();  
  301.                     if (onSelectListener != null)  
  302.                         onSelectListener.endSelect(itemList.get(i).id,  
  303.                                 itemList.get(i).itemText);  
  304.                     break;  
  305.                 }  
  306.             }  
  307.         } else {  
  308.             for (int i = itemList.size() - 1; i >= 0; i--) {  
  309.                 if (itemList.get(i).isSelected()) {  
  310.                     newMove = (int) itemList.get(i).moveToSelected();  
  311.                     if (onSelectListener != null)  
  312.                         onSelectListener.endSelect(itemList.get(i).id,  
  313.                                 itemList.get(i).itemText);  
  314.                     break;  
  315.                 }  
  316.             }  
  317.         }  
  318.         for (ItemObject item : itemList) {  
  319.             item.newY(move + 0);  
  320.         }  
  321.         slowMove(newMove);  
  322.         Message rMessage = new Message();  
  323.         rMessage.what = REFRESH_VIEW;  
  324.         handler.sendMessage(rMessage);  
  325.   
  326.     }  
  327.   
  328.     /*** 缓慢移动*/  
  329.     private synchronized void slowMove(final int move) {  
  330.         new Thread(new Runnable() {  
  331.   
  332.             @Override  
  333.             public void run() {  
  334.                 // 判断正负  
  335.                 int m = move > 0 ? move : move * (-1);  
  336.                 int i = move > 0 ? 1 : (-1);  
  337.                 // 移动速度  
  338.                 int speed = 1;  
  339.                 while (true) {  
  340.                     m = m - speed;  
  341.                     if (m <= 0) {  
  342.                         for (ItemObject item : itemList) {  
  343.                             item.newY(m * i);  
  344.                         }  
  345.                         Message rMessage = new Message();  
  346.                         rMessage.what = REFRESH_VIEW;  
  347.                         handler.sendMessage(rMessage);  
  348.                         try {  
  349.                             Thread.sleep(2);  
  350.                         } catch (InterruptedException e) {  
  351.                             e.printStackTrace();  
  352.                         }  
  353.                         break;  
  354.                     }  
  355.                     for (ItemObject item : itemList) {  
  356.                         item.newY(speed * i);  
  357.                     }  
  358.                     Message rMessage = new Message();  
  359.                     rMessage.what = REFRESH_VIEW;  
  360.                     handler.sendMessage(rMessage);  
  361.                     try {  
  362.                         Thread.sleep(2);  
  363.                     } catch (InterruptedException e) {  
  364.                         e.printStackTrace();  
  365.                     }  
  366.                 }  
  367.                 for (ItemObject item : itemList) {  
  368.                     if (item.isSelected()) {  
  369.                         if (onSelectListener != null)  
  370.                             onSelectListener.endSelect(item.id, item.itemText);  
  371.                         break;  
  372.                     }  
  373.                 }  
  374.   
  375.             }  
  376.         }).start();  
  377.     }  
  378.   
  379.     /** 
  380.      * 移动到默认位置 
  381.      * 
  382.      * @param move 
  383.      */  
  384.     private void defaultMove(int move) {  
  385.         for (ItemObject item : itemList) {  
  386.             item.newY(move);  
  387.         }  
  388.         Message rMessage = new Message();  
  389.         rMessage.what = REFRESH_VIEW;  
  390.         handler.sendMessage(rMessage);  
  391.     }  
  392.     /*** 滑动监听*/  
  393.     private void onSelectListener() {  
  394.         if (onSelectListener == null)  
  395.             return;  
  396.         for (ItemObject item : itemList) {  
  397.             if (item.isSelected()) {  
  398.                 onSelectListener.selecting(item.id, item.itemText);  
  399.             }  
  400.         }  
  401.     }  
  402.     /*** 设置数据 (第一次)*/  
  403.     public void setData(ArrayList<String> data) {  
  404.         this.dataList = data;  
  405.         initData();  
  406.     }  
  407.     /*** 获取返回项 id*/  
  408.     public int getSelected() {  
  409.         for (ItemObject item : itemList) {  
  410.             if (item.isSelected())  
  411.                 return item.id;  
  412.         }  
  413.         return -1;  
  414.     }  
  415.     /*** 获取返回的内容*/  
  416.     public String getSelectedText() {  
  417.         for (ItemObject item : itemList) {  
  418.             if (item.isSelected())  
  419.                 return item.itemText;  
  420.         }  
  421.         return "";  
  422.     }  
  423.     /*** 是否可用*/  
  424.     public boolean isEnable() {  
  425.         return isEnable;  
  426.     }  
  427.     /*** 设置是否可用*/  
  428.     public void setEnable(boolean isEnable) {  
  429.         this.isEnable = isEnable;  
  430.     }  
  431.     /*** 设置默认选项*/  
  432.     public void setDefault(int index) {  
  433.         if (index > itemList.size() - 1)  
  434.             return;  
  435.         float move = itemList.get(index).moveToSelected();  
  436.         defaultMove((int) move);  
  437.     }  
  438.     /*** 获取列表大小*/  
  439.     public int getListSize() {  
  440.         if (itemList == null)  
  441.             return 0;  
  442.         return itemList.size();  
  443.     }  
  444.     /** 监听*/  
  445.     public void setOnSelectListener(OnSelectListener onSelectListener) {  
  446.         this.onSelectListener = onSelectListener;  
  447.     }  
  448.   
  449.     @SuppressLint("HandlerLeak")  
  450.     Handler handler = new Handler() {  
  451.   
  452.         @Override  
  453.         public void handleMessage(Message msg) {  
  454.             super.handleMessage(msg);  
  455.             switch (msg.what) {  
  456.                 case REFRESH_VIEW:  
  457.                     invalidate();  
  458.                     break;  
  459.                 default:  
  460.                     break;  
  461.             }  
  462.         }  
  463.   
  464.     };  
  465.   
  466.     /*** 单条内容*/  
  467.     private class ItemObject {  
  468.         /**id*/  
  469.         public int id = 0;  
  470.         /*** 内容*/  
  471.         public String itemText = "";  
  472.         /*** x坐标*/  
  473.         public int x = 0;  
  474.         /*** y坐标*/  
  475.         public int y = 0;  
  476.         /*** 移动距离*/  
  477.         public int move = 0;  
  478.         /*** 字体画笔*/  
  479.         private TextPaint textPaint;  
  480.         /*** 字体范围矩形*/  
  481.         private Rect textRect;  
  482.   
  483.         public ItemObject() {  
  484.             super();  
  485.         }  
  486.   
  487.         /** 
  488.          * 绘制自身 
  489.          * 
  490.          * @param canvas         画板 
  491.          * @param containerWidth 容器宽度 
  492.          */  
  493.         public void drawSelf(Canvas canvas, int containerWidth) {  
  494.   
  495.             if (textPaint == null) {  
  496.                 textPaint = new TextPaint();  
  497.                 textPaint.setAntiAlias(true);  
  498.             }  
  499.   
  500.             if (textRect == null)  
  501.                 textRect = new Rect();  
  502.   
  503.             // 判断是否被选择  
  504.             if (isSelected()) {  
  505.                 textPaint.setColor(selectedColor);  
  506.                 // 获取距离标准位置的距离  
  507.                 float moveToSelect = moveToSelected();  
  508.                 moveToSelect = moveToSelect > 0 ? moveToSelect : moveToSelect * (-1);  
  509.                 // 计算当前字体大小  
  510.                 float textSize = normalFont  
  511.                         + ((selectedFont - normalFont) * (1.0f - moveToSelect / (float) unitHeight));  
  512.                 textPaint.setTextSize(textSize);  
  513.             } else {  
  514.                 textPaint.setColor(normalColor);  
  515.                 textPaint.setTextSize(normalFont);  
  516.             }  
  517.   
  518.             // 返回包围整个字符串的最小的一个Rect区域  
  519.             itemText = (String) TextUtils.ellipsize(itemText, textPaint, containerWidth, TextUtils.TruncateAt.END);  
  520.             textPaint.getTextBounds(itemText, 0, itemText.length(), textRect);  
  521.             // 判断是否可视  
  522.             if (!isInView())  
  523.                 return;  
  524.   
  525.             // 绘制内容  
  526.             canvas.drawText(itemText, x + controlWidth / 2 - textRect.width() / 2,  
  527.                     y + move + unitHeight / 2 + textRect.height() / 2, textPaint);  
  528.   
  529.         }  
  530.   
  531.         /*** 是否在可视界面内*/  
  532.         public boolean isInView() {  
  533.             if (y + move > controlHeight || (y + move + unitHeight / 2 + textRect.height() / 2) < 0)  
  534.                 return false;  
  535.             return true;  
  536.         }  
  537.   
  538.         /*** 移动距离*/  
  539.         public void move(int _move) {  
  540.             this.move = _move;  
  541.         }  
  542.   
  543.         /*** 设置新的坐标*/  
  544.         public void newY(int _move) {  
  545.             this.move = 0;  
  546.             this.y = y + _move;  
  547.         }  
  548.   
  549.         /*** 判断是否在选择区域内*/  
  550.         public boolean isSelected() {  
  551.             if ((y + move) >= controlHeight / 2 - unitHeight / 2 + lineHeight  
  552.                     && (y + move) <= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  553.                 return true;  
  554.             }  
  555.             if ((y + move + unitHeight) >= controlHeight / 2 - unitHeight / 2 + lineHeight  
  556.                     && (y + move + unitHeight) <= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  557.                 return true;  
  558.             }  
  559.             if ((y + move) <= controlHeight / 2 - unitHeight / 2 + lineHeight  
  560.                     && (y + move + unitHeight) >= controlHeight / 2 + unitHeight / 2 - lineHeight) {  
  561.                 return true;  
  562.             }  
  563.             return false;  
  564.         }  
  565.   
  566.         /*** 获取移动到标准位置需要的距离*/  
  567.         public float moveToSelected() {  
  568.             return (controlHeight / 2 - unitHeight / 2) - (y + move);  
  569.         }  
  570.     }  
  571.   
  572.     /*** 选择监听*/  
  573.     public interface OnSelectListener {  
  574.         /*** 结束选择*/  
  575.         void endSelect(int id, String text);  
  576.         /*** 选中的内容*/  
  577.         void selecting(int id, String text);  
  578.   
  579.     }  
  580. }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值