【发布时间】:2016-03-24 00:38:35
【问题描述】:
是否可以在 numberpicker 中更改所选项目的颜色,以便每次出现新的中心子 TextView 时将其颜色更改为我喜欢的任何颜色,我没有找到任何样式或 API 公开?
【问题讨论】:
标签: android
是否可以在 numberpicker 中更改所选项目的颜色,以便每次出现新的中心子 TextView 时将其颜色更改为我喜欢的任何颜色,我没有找到任何样式或 API 公开?
【问题讨论】:
标签: android
我认为您可以使用小部件的setOnValueChangedListener(...)方法来使用NumberPicker.OnValueChangeListener。
在回调中你会得到picker 并且可以改变你想要的样式。
【讨论】:
我想出了如何仅为选定的数字更改颜色r。在 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){
}
}
}
}
【讨论】:
您可以尝试使用以下代码。只需在此参数中传递您的 NumberPicker 和颜色即可。希望这能解决您的问题
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();
}
【讨论】:
根据设计无法更改仅更改中心颜色。如果您查看 NumberPicker 的源代码,特别是在 onDraw 方法中,那么您将看到小部件在呈现时在中心项和其余项之间没有区别。所有文本都使用相同的颜色呈现。
源代码链接。检查从注释“//draw the selector wheel”开始的onDraw方法:https://android.googlesource.com/platform/frameworks/base/+/0e2d281/core/java/android/widget/NumberPicker.java
此外,在编辑时,它会在 NumberPicker 中心区域的顶部放置一个 EditText 控件。更改此类 EditText 控件不会解决问题,即使您执行一些技巧,例如执行编程单击以将 EditText 设置为焦点,因为一旦您再次滚动或将焦点设置到布局中的不同视图,EditText将被隐藏,您将失去这种色彩效果。
唯一的解决方案是创建一个新的 NumberPicker 控件。例如,您可以使用实际的 NumberPicker 源代码,并根据您的需要对其进行调整。您需要在 onDraw 方法中进行调整。
【讨论】: