【问题标题】:opacity of textview in androidandroid中textview的不透明度
【发布时间】:2013-02-11 22:23:13
【问题描述】:

在我的应用程序中,最初我将 TextView 的不透明度设置为 60。 之后,当用户按下按钮时,我想根据按下增加它的按钮或减少它的按钮来减少或增加TextView 的不透明度。 我试过这个,但每次当我得到文本的不透明度时,它的 -3 或 -1 实际上不是。

 public void decreaseOpacity(View v){

    int op=txtView.getBackground().getOpacity();// its alwz -ve value
    txtView.getBackground().setAlpha(op-1);

}

【问题讨论】:

    标签: android textview opacity


    【解决方案1】:

    试试这个代码

    public class AlphaTextView extends TextView {
    
      public AlphaTextView(Context context) {
        super(context);
      }
    
      public AlphaTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
      }
    
      public AlphaTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
      }
    
      @Override
      public boolean onSetAlpha(int alpha) {
        setTextColor(getTextColors().withAlpha(alpha));
        setHintTextColor(getHintTextColors().withAlpha(alpha));
        setLinkTextColor(getLinkTextColors().withAlpha(alpha));
        return true;
      }
    }
    

    【讨论】:

      【解决方案2】:

      Drawable.getOpacity() 不考虑 setAlpha() 所做的更改。 See the docs:

      请注意,返回值不考虑自定义 alpha 或已由客户通过 setAlpha(int) 或 setColorFilter(ColorFilter) 方法。

      您可能需要将 alpha 值存储为变量而不使用 getOpacity(),例如:

      private int mTextViewAlpha = 255;
      
      public void decreaseOpacity(View v){
          if ( mTextViewAlpha-- <= 0 ) mTextViewAlpha = 0;
          txtView.getBackground().setAlpha(mTextViewAlpha);
          txtView.getBackground().invalidateSelf();
      }
      

      【讨论】:

      • 我添加了简单的例子。请注意,我没有编译它,所以可能有错别字;)
      • &gt;= 更改为&lt;=,所以现在可能会更好。就像他说的,错别字是可能的。
      • 是的,谢谢 Geobits :) 另外,我添加了 invalidateSelf() 调用来强制背景重绘。现在我已经确认它有效。如果你想让背景更快变得透明,请从 mTextViewAlpha 中减去 1 以上。
      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2012-11-15
      • 2013-11-08
      • 1970-01-01
      • 2016-10-12
      • 2014-01-05
      相关资源
      最近更新 更多