【问题标题】:TextView as a progressbar with textcolor minipulation?TextView 作为带有文本颜色操作的进度条?
【发布时间】:2013-02-05 07:45:00
【问题描述】:

我正在努力改进我的应用的用户界面。 在我使用的设计中,我有一个 TextView,它将在特定时间充当进度条。 ruslt 应该是这样的:

问题是部分文本会随着进度的变化而改变颜色

我查看了 android 中的 spannablestring,如果我能找到进度所涵盖的字母,它会起作用(但我认为这并不容易/准确)

我现在打算做的是使用以下内容:

  • FrameLayout 与:
  • 带有绿色文本和白色背景的背景 textView。
  • 在前进时改变宽度的前端线性布局。
  • TextView 具有绿色背景和与框架布局宽度匹配的白色文本。

有更好的方法吗?

【问题讨论】:

    标签: android android-layout user-interface animation android-progressbar


    【解决方案1】:

    我知道这是一个老问题,但我发布这个问题是因为它可能会帮助其他人寻找类似的情况,希望它会帮助现在解决这个问题的人。这是一个例子

    我的解决方案基本上是使用drawText 在画布中绘图。这里的技巧是您绘制两个文本,一个在条形边界内,一个在视图边界内,并使用以下 Z-index 顺序(根据使用的示例):

    • 文字(白色)
    • 红条
    • 文字(黑色)
    • 查看背景

    我已经做了一个关于如何实现这个的例子,在这个示例/库中,我使用了一个自定义的 imageview 来做到这一点。随意使用它:https://github.com/danilodanicomendes/InvertedTextProgressBar

    【讨论】:

      【解决方案2】:

      更好的方法需要您覆盖 TextView 类。您可以使用剪辑,拆分 TextView 并以不同的颜色绘制两个部分。

      TextView tv = new TextView(this){
          @Override
          public void draw(Canvas canvas) {
              int color1 = Color.WHITE;
              int color2 = Color.GREEN;
      
              canvas.save();
              setTextColor(color1);
              setBackgroundColor(color2);
              canvas.clipRect(new Rect(0, 0, (int)(getWidth() * percent), getHeight()));
              super.draw(canvas);
              canvas.restore();
      
              canvas.save();
              setTextColor(color2);
              setBackgroundColor(color1);
              canvas.clipRect(new Rect((int)(getWidth() * percent), 0, getWidth(), getHeight()));
              super.draw(canvas);
              canvas.restore();
          }  
      };
      

      我希望你明白这一点

      【讨论】:

      • 只需添加 canvas.restore();每次抽奖后,代码就可以运行了
      • 是的,我没有时间测试它:) 谢谢
      • 由于某种原因,当我尝试上面的代码时,文本颜色成功更改,但背景仍然是 colour1
      • 请注意,setTextColor() 会导致 invalidate() 调用。您的视图将不断重绘。
      【解决方案3】:

      最简单的解决方案是在相对布局上使用 ProgressBar 和 TextView。 您为两者提供自己的风格,仅此而已。当 ProgressBar 拥有您所需要的一切时,尝试在 TextView 上执行此操作是没有意义的。你的布局应该是这样的:

      <RelativeLayout android:layout_width="match_parent"
              android:layout_height="wrap_content">
      
              <ProgressBar android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:layout_centerVertical="true"/>
      
              <TextView android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:text="Doing something"
                  android:gravity="center"
                  android:layout_centerVertical="true"/>          
      </RelativeLayout>
      

      您只需要根据需要调整宽度和高度 :)

      【讨论】:

        猜你喜欢
        • 2011-07-07
        • 2012-12-01
        • 1970-01-01
        • 2011-09-27
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多