2012-01-12 131 views
8

所以我试图动态更改我的android应用中的TextView的不透明度。我有一个seekbar,当我将拇指向右滑动时,TextView下面的分层应该开始变得透明。当拇指到达seekbar的大约一半时,文本应该完全透明。我试图使用从我的TextView上的View继承的setAlpha(float)方法,但Eclipse告诉我setAlpha()对于TextView类型是未定义的。我是否以错误的方式调用该方法?还是有另一种方法来改变不透明度?在Android中更改TextView的不透明度

这是我的代码(classicTextTextViewgameSelectorseekbar):

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch){ 
    classicText.setAlpha(gameSelector.getProgress()); 
} 

回答

37

,你可以这样设置

int alpha = 0; 
((TextView)findViewById(R.id.t1)).setTextColor(Color.argb(alpha, 255, 0, 0)); 

,你从将被设置成文本颜色

5

变化方法以下

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) 
{ 
    classicText.setAlpha((float)(gameSelector.getProgress())/(float)(seekBar.getMax())); 
} 
+0

这不工作AFAIK。我已经尝试过了.TextView没有名为setAlpha()的方法,请在回答前检查它! – Hiral 2012-01-12 05:24:41

+0

检查方法http://developer.android.com/reference/android/view/View.html#setAlpha(float) – jeet 2012-01-12 05:31:51

+0

这是正确的参考,但你不能在你的eclipse中直接使用这种方法来浏览或查看你的eclipse请检查自己。相反,您需要自定义textview,然后在您的应用中使用该类。 – Hiral 2012-01-12 05:52:50

-1

View.setAlpha(浮动XXX);

xxx - 0 - 255的范围,0是透明的,255是不透明的。

int progress = gameSelector.getProgress(); 
int maxProgress = gameSelector.getMax(); 
float opacity = (progress/maxProgress)*255; 
classicText.setAlpha(opacity); 
9

这为我工作搜索条获取阿尔法阿尔法:

1.创建类AlphaTextView.class

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)); 
    getBackground().setAlpha(alpha); 
    return true; 
    }  
} 

2.添加这个,而不是使用TextView的在你的XML创建一个TextView:

... 
    <!--use complete path to AlphaTextView in following tag--> 
    <com.xxx.xxx.xxx.AlphaTextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="sample alpha textview" 
     android:gravity="center" 
     android:id="@+id/at" 
     android:textColor="#FFFFFF" 
     android:background="#88FF88" 
     /> 
... 

3.现在你可以使用这个TextView的在你的活动,如:

at=(AlphaTextView)findViewById(R.id.at); 

at.onSetAlpha(255); // To make textview 100% opaque 
at.onSetAlpha(0); //To make textview completely transperent 
+0

我使用了这种变化来改变文本阿尔法而不改变背景阿尔法,谢谢! – 2018-01-12 22:08:08