肆意先生
2018-08-20 15:55:58浏览 1981
public class NumberPickerCompat extends NumberPicker implements NumberPicker.OnScrollListener,NumberPicker.OnValueChangeListener{
private OnNumberPickerChangedListener mListener;
private int selected;
public NumberPickerCompat(Context context) {
super(context);
init();
}
public NumberPickerCompat(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public NumberPickerCompat(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public NumberPickerCompat(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
this.setOnScrollListener(this);
this.setOnValueChangedListener(this);
}
public void setNumberPickerChangedListener(OnNumberPickerChangedListener listener){
mListener = listener;
}
/**
* 通过反射改变分割线颜色,
*/
public void setPickerDividerColor(int color) {
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try{
pf.set(this,new ColorDrawable(color));
}catch (IllegalAccessException e) {
e.printStackTrace();
}catch (Resources.NotFoundException e) {
e.printStackTrace();
}catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}
/**
* 过反射改变文字的颜色
*/
public void setPickerTextColor(int color) {
final int count = getChildCount();
for(int i = 0; i < count; i++){
View child = getChildAt(i);
if(child instanceof EditText){
try{
Field selectorWheelPaintField = getClass().getSuperclass().getDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.setAccessible(true);
((Paint)selectorWheelPaintField.get(this)).setColor(color);
((EditText)child).setTextColor(color);
invalidate();
}
catch(NoSuchFieldException e){
e.printStackTrace();
}
catch(IllegalAccessException e){
e.printStackTrace();
}
catch(IllegalArgumentException e){
e.printStackTrace();
}
}
}
}
@Override
public void onScrollStateChange(NumberPicker view, int scrollState) {
switch (scrollState){
case SCROLL_STATE_TOUCH_SCROLL:
mListener.startScroll(this);
break;
case SCROLL_STATE_FLING:
break;
case SCROLL_STATE_IDLE:
mListener.stopScroll(this,selected,getDisplayedValues() != null ? true : false);
break;
}
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mListener.scrolling(this,newVal,getDisplayedValues() != null ? true : false);
selected = newVal;
}
public interface OnNumberPickerChangedListener{
public void startScroll(NumberPickerCompat picker);
public void scrolling(NumberPickerCompat picker,int selected,boolean isPosition);
public void stopScroll(NumberPickerCompat picker,int selected,boolean isPosition);
}
}