37

我一直在寻找解决我的问题的方法。但我的代码似乎没问题。

我将尝试解释:我的布局定义中有一个带有 android:alpha="0" 的 TextView。我想(当单击图像时)显示带有 AlphaAnimation 的 TextView,从 0.0f 到 1.0f。

我的问题是,当我单击图像时,什么也没有发生。但奇怪的是,如果我在布局定义中将它的 alpha 设置为 1,然后单击图像,我可以看到动画(alpha 1 -> alpha 0 -> alpha 1)。

我究竟做错了什么?

我的代码:

TextView tv = (TextView) findViewById(R.id.number);

AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
animation1.setDuration(1000);
animation1.setFillAfter(true);
tv.startAnimation(animation1);

提前致谢。

4

4 回答 4

83

问题出在android:alpha="0". 此属性设置 View http://developer.android.com/reference/android/view/View.html#attr_android:alpha的透明度

当 alpha 属性等于 0 时,动画将透明度从 更改0*0.0f=00*1.0f=0。当 alpha 属性设置为 1 时,动画将透明度从 更改1*0.0f=01*1.0f=1。这就是为什么在第一种情况下您看不到文本,而在第二种情况下一切都按预期工作。

为了使事情正常工作,您必须在布局 xml 中将可见性属性设置为不可见。在开始 alpha 动画调用之前tv.setVisibility(View.VISIBLE);

于 2012-07-08T21:57:40.960 回答
19

答案中提供了更简单的方法:

tv.animate().alpha(1).setDuration(1000);
于 2016-04-05T08:53:02.917 回答
0

实际上,android 有两个用于视图的 alpha 属性

    /**
     * The opacity of the View. This is a value from 0 to 1, where 0 means
     * completely transparent and 1 means completely opaque.
     */
    @ViewDebug.ExportedProperty
    float mAlpha = 1f;

    /**
     * The opacity of the view as manipulated by the Fade transition. This is a hidden
     * property only used by transitions, which is composited with the other alpha
     * values to calculate the final visual alpha value.
     */
    float mTransitionAlpha = 1f;


/**
 * Calculates the visual alpha of this view, which is a combination of the actual
 * alpha value and the transitionAlpha value (if set).
 */
private float getFinalAlpha() {
    if (mTransformationInfo != null) {
        return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha;
    }
    return 1;
}

视图最终 alpha 是两个 alpha 的乘积

View#setAlpha(float) & View#animate() & android:alpha -> mAlpha

AlphaAnimation -> mTransitionAlpha

于 2019-09-06T09:53:56.887 回答
0

fillBefore动画的属性设置为 true 为我解决了这个问题。

TextView tv = (TextView) findViewById(R.id.number);

AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
animation1.setDuration(1000);
animation1.setFillBefore(true);
tv.startAnimation(animation1);

FillBefore在开始动画之前设置转换。

于 2021-01-01T08:47:44.560 回答