【问题标题】:Is it possible to add a setOnColorChangeListener for a TextView in Android?是否可以在 Android 中为 TextView 添加 setOnColorChangeListener?
【发布时间】:2020-09-26 00:22:28
【问题描述】:

例如,我想打印一个Toast -->COLOR CHANGEDTextView 的textColor 时。这可能吗?

【问题讨论】:

    标签: java android textview


    【解决方案1】:

    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。

    希望这会有所帮助。如果您不理解/想要建议,请随时发表评论。 编码愉快!

    【讨论】:

    • 您好,谢谢!看来我需要这样的东西!但我不能让它工作!当我开始输入 yourCustomTextView.setOnColo[...] setOnColor.... 时变为红色。好像找不到。
    • 嗨@F.Mysir,您是否正确遵循了我上面设置的说明?您是否已将您的 TextView 从 Android-default TextView 类更改为您的自定义 TextView 类?
    【解决方案2】:

    您可能在为文本视图设置新颜色的相同方法中添加回调。

    示例

    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

    【讨论】:

    • 我看过这篇文章。 stackoverflow.com/questions/8292712/… 但我不确定如何创建自定义侦听器...
    • 颜色的变化来自外部,在我的情况下是随机的......
    • 您可以使用默认的 TextView 并使用上述方法,也可以创建整个自定义 textview 并覆盖 setTextColor 并在其中注册回调方法(因此使用这种方式您必须使用自定义textview 而不是使用默认的)。因此,在您的自定义视图中,每次调用 setTextColor 时都会调用该回调。请参考本指南创建自定义视图 -- developer.android.com/training/custom-views/create-view
    • @F.Mysir 查看我的回答,了解如何使用自定义 TextView 实现您想要的目标
    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多