【发布时间】:2020-09-26 00:22:28
【问题描述】:
例如,我想打印一个Toast -->COLOR CHANGEDTextView 的textColor 时。这可能吗?
【问题讨论】:
例如,我想打印一个Toast -->COLOR CHANGEDTextView 的textColor 时。这可能吗?
【问题讨论】:
AFAIK,没有记录在案的官方方法来实现你想要的。 但我可能会为此建议一种解决方法,尽管这有点矫枉过正。我保证这个答案的灵活性,因为它几乎适用于涉及 TextView 使用的任何用例。
您可以通过扩展 TextView 类来创建自定义 TextView,并在自定义 TextView 类中添加一个自定义接口,该接口可用于应用颜色更改侦听器。像这样:
public class MyCustomTextView extends TextView {
// other code, but you not need it since it's already inherited from the parent; unless you want to customize them too.
public interface OnColorChangeListener {
void onColorChanged()
}
private OnColorChangeListener onColorChangeListener;
// a public method to apply a color change listener interface to your TextView
public void setOnColorChangeListener(OnColorChangeListener onColorChangeListener) {
this.onColorChangeListener = onColorChangeListener;
}
public void setTextColor() {
// REMEMBER & BE AWARE: this is the original TextView method for setting a color.
// here you can call the listener onColorChanged() method.
onColorChangeListener.onColorChanged()
}
}
下一步是将 XML 布局文件中的 TextView 更改为此自定义 TextView 类。然后,在您想要监听颜色变化的活动/片段中,您可以像这样简单地进行操作:
yourCustomTextView.setOnColorChangeListener(new MyCustomTextView.OnColorChangeListener() {
void onColorChanged() {
Toast.makeText(context, "Your text", Toast.LENGTH_SHORT).show();
}
});
使用这样的方法,每次更改自定义 TextView 的颜色时,都会显示 toast。
希望这会有所帮助。如果您不理解/想要建议,请随时发表评论。 编码愉快!
【讨论】:
您可能在为文本视图设置新颜色的相同方法中添加回调。
示例
public void setNewTextColor(int color) {
yourTextView.setTextColor(color);
yourCallbackMethod();
}
public void yourCallbackMethod() {
//you can do whatever in this method
}
更新 - 您可以添加自定义文本视图并通过覆盖自定义文本视图类中的 setTextColor 方法来定义回调。
在android中创建自定义视图的官方指南-https://developer.android.com/training/custom-views/create-view
【讨论】: