TimePicker,TimePickerDialog以及自定义timepicker(一)

TimePicker,TimePickerDialog以及自定义timepicker(一)

场景:在activity上点击,弹出一个dialog,然后点击dialog上的一个按钮,在弹出时间。以及自定义dialog

懒,要用到一个选择时间的需求,只要求小时和分钟,弹出式,第一时间想到了timepicker以及numberpicker,

先用timepicker,发现在4.0黑色丑死了,4.4正常想要的以及5.0上是钟摆,用

timepickerdialog比timepicker多个上午和下午,算了还是自定义吧:

很晚了,直接贴代码关于布局等后面会仔细研究学习的:

主activity:

package com.example.onebelowzero;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{

private Button mBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();
}

private MyCustomDialog dialog;

private void init() {
mBtn = (Button) findViewById(R.id.btn);
mBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn:
doIt();

break;

default:
break;
}
}

private void doIt(){
/**
* 此时样式好丑,我们在清单文件中改下主题即可 不一定要在appli。。上改,在activity上改即可
* android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar.Fullscreen"
*/
dialog = new MyCustomDialog(this, R.style.CustomDialog);
dialog.setContentView(R.layout.dialog_mycustom);
dialog.show();
}

}

=====================

MyCustomDialog :

package com.example.onebelowzero;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.onebelowzero.MyPickerView.onSelectListener;

/**
自定义dialog
*/
public class MyCustomDialog extends Dialog implements android.view.View.OnClickListener{

private Context context;
private LeaveMyDialogListener listener;
public interface LeaveMyDialogListener {
public void onClick(View view);

public void refreshUI(String timer);
}

public MyCustomDialog(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
}

public MyCustomDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
this.context = context;
}

public MyCustomDialog(Context context, int theme, LeaveMyDialogListener listener) {
super(context, theme);
// TODO Auto-generated constructor stub
this.context = context;
this.listener = listener;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

initView();
}

private void initView() {
// TODO Auto-generated method stub
Button showPicker = (Button) findViewById(R.id.dialog_activity);
showPicker.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dateDialog();
// dateDialog2();
// dateDialog3();

}
/**
* 弹出4.0,4.4,5.0TimePicker样式各不一样
*/
private void dateDialog() {
TimePickerDialog time = new TimePickerDialog(context,
new OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// TODO Auto-generated method stub
Toast.makeText(context,
hourOfDay + "hour " + minute + "minute",
Toast.LENGTH_SHORT).show();
}
}, 18, 25, true);

time.show();
}

/**
* 方式二和方式一差不多
*/
private void dateDialog2() {
final TimePicker mDatePicker = new TimePicker(context);

AlertDialog.Builder timeDialog = new AlertDialog.Builder(context);
// timeDialog.setTitle("一座城池2012");
timeDialog.setIcon(null);
timeDialog.setCancelable(false);
timeDialog.setView(mDatePicker);
timeDialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 取出TimePicker设定的时间就行了
mDatePicker.getCurrentHour();
mDatePicker.getCurrentMinute();
}
}).create();
timeDialog.show();
}

/**
* 方式三采取自定义view将弹出的样式设置成我们想要的
*/
MyPickerView hour;
MyPickerView minute;
private void dateDialog3() {
View view = this.getLayoutInflater().inflate(R.layout.mypicker_dialog,
null);
hour = (MyPickerView) view.findViewById(R.id.minute_pv);
minute = (MyPickerView) view.findViewById(R.id.second_pv);
//创建两个集合分别用来装长度 我们的MyPickerView继承view 没有 void onTimeChanged(TimePicker view, int hourOfDay, int minute);

List<String> data = new ArrayList<String>();
List<String> seconds = new ArrayList<String>();
for (int i = 0; i < 24; i++) {
data.add(i<10?"0" + i:""+i);//添加0
}
for (int i = 0; i < 60; i++) {
seconds.add(i < 10 ? "0" + i : "" + i);
}

hour.setData(data);
hour.setOnSelectListener(new onSelectListener() {

@Override
public void onSelect(String text) {
// TODO Auto-generated method stub
//获取分钟
}
});
minute.setData(seconds);
minute.setOnSelectListener(new onSelectListener() {

@Override
public void onSelect(String text) {
Toast.makeText(context, "选择了 " + text + " 分",
Toast.LENGTH_SHORT).show();

}
});

AlertDialog.Builder timeDialog = new AlertDialog.Builder(context);
timeDialog.setTitle("一座城池2012");
timeDialog.setIcon(null);
timeDialog.setCancelable(false);
/**
* 添加view
*/
timeDialog.setView(view);
timeDialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 取出MyTimePicker设定的时间就行了

}
}).create();
timeDialog.show();
}

========================

}

=======================

MyPickerView :::

package com.example.onebelowzero;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

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;

public class MyPickerView 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<String> mDataList;
/**
* 选中的位置,这个位置是mDataList的中心位置,一直不变
*/
private int mCurrentSelected;
private Paint mPaint;

private float mMaxTextSize = 80;
private float mMinTextSize = 40;

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 MyPickerView(Context context) {
super(context);
init();
}

public MyPickerView(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<String> datas) {
mDataList = datas;
mCurrentSelected = datas.size() / 2;
invalidate();
}

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();
}

private void moveHeadToTail() {
String head = mDataList.get(0);
mDataList.remove(0);
mDataList.add(head);
}

private void moveTailToHead() {
String 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 / 4.0f;
mMinTextSize = mMaxTextSize / 2f;
isInit = true;
invalidate();
}

private void init() {
timer = new Timer();
mDataList = new ArrayList<String>();
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Style.FILL);
mPaint.setTextAlign(Align.CENTER);
mPaint.setColor(mColorText);
}

@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));

canvas.drawText(mDataList.get(mCurrentSelected), 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));
canvas.drawText(mDataList.get(mCurrentSelected + type * position),
(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());
}
}

/**
* 定义接口用来选择
* @author kcw001
*/
public interface onSelectListener {
void onSelect(String text);
}
}

布局文件等不贴了,见完整代码:

http://download.csdn.net/detail/onebelowzero2012/9374740

上一篇:BZOJ_4590_[Shoi2015]自动刷题机_二分答案


下一篇:【转】【DP_树形DP专辑】【9月9最新更新】【from zeroclock's blog】