在NumberPicker中,是否有可能更改所选项目的颜色,使每次出现新的中心子TextView时更改其颜色为我喜欢的颜色?我没有找到任何样式或API可以公开关于这个问题。
在NumberPicker中,是否有可能更改所选项目的颜色,使每次出现新的中心子TextView时更改其颜色为我喜欢的颜色?我没有找到任何样式或API可以公开关于这个问题。
我找到了如何仅更改所选数字的颜色。在您的NumberPicker中设置OnTouchListener即可。
numberPicker.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(final View v, MotionEvent event) {
currentTouchAction = event.getAction();
if (currentTouchAction == MotionEvent.ACTION_UP) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (currentTouchAction == MotionEvent.ACTION_UP) {
setSelectedTextColor((NumberPicker)v, selectedColorRes);
}
}
}, 300);
}
return false;
}
});
以下代码是用于更改所选数字颜色的。您可能需要使用'performClick()'动态应用颜色。
如果您这样做,选择器将立即停止。这就是为什么我在上面放置了postDelayed(300)的原因。用户可能会多次拖动数值选择器以选择利润数字。如果您在上面使用postDelay()并等待几毫秒,它可以平稳滚动。
public void setSelectedTextColor(NumberPicker np, int colorRes) {
final int count = np.getChildCount();
for(int i = 0; i < count; i++){
View child = np.getChildAt(i);
if(child instanceof EditText){
try{
Field selectorWheelPaintField = np.getClass().getDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.setAccessible(true);
((EditText) child).setTextColor(mContext.getResources().getColor(colorRes));
np.performClick();
}
catch(NoSuchFieldException e){
}
catch(IllegalArgumentException e){
}
}
}
}
我认为你可以使用小部件的方法setOnValueChangedListener(...)
,并使用NumberPicker.OnValueChangeListener
进行回调。
在回调中,您可以获取picker
并按照您想要的方式更改样式。
import java.lang.reflect.Field;
public static void changeNumberPickerTextColor(NumberPicker numberPicker, int color)
{
try{
Field selectorWheelPaintField = numberPicker.getClass()
.getDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.setAccessible(true);
((Paint)selectorWheelPaintField.get(numberPicker)).setColor(color);
}
catch(NoSuchFieldException e){
Log.w("setNumberPickerTextColor", e);
}
catch(IllegalAccessException e){
Log.w("setNumberPickerTextColor", e);
}
catch(IllegalArgumentException e){
Log.w("setNumberPickerTextColor", e);
}
final int count = numberPicker.getChildCount();
for(int i = 0; i < count; i++){
View child = numberPicker.getChildAt(i);
if(child instanceof EditText)
((EditText)child).setTextColor(color);
}
numberPicker.invalidate();
}