将代码转换为可重用的类 - Android

时间:2015-03-13 13:09:35

标签: android android-layout android-animation

我使用以下代码来动画TextView的高度从0增加到100(或者在animateHeight方法中指定为" m"值。我的问题是,我怎么能把它变成一个类,这样我就可以为我的所有12个文本视图调用它,并让它们同时具有动画效果?

@SuppressLint("NewApi")
private void animateHeight(int m) {        
    int maxInDp = m;
    int maxInPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, maxInDp, getResources().getDisplayMetrics());
    ObjectAnimator objectAnimator = ObjectAnimator.ofInt(this, "barHeight", maxInPx);
    objectAnimator.setDuration(1500);
    objectAnimator.setInterpolator(new AccelerateInterpolator(1.0f));
    objectAnimator.start(); 
}

public int barHeight = 0;

public int getBarHeight() { return barHeight; }

public void setBarHeight(int height) {
    barHeight = height;
    ViewGroup.LayoutParams params = lblSavingsSummaryChartMonth1Savings.getLayoutParams();
    params.height = barHeight;
    lblSavingsSummaryChartMonth1Savings.setLayoutParams(params);
}

更新

我已经尝试使用下面的代码创建我自己的自定义TextView,但是我得到一个静态错误" static"是不允许的。如果我删除它,错误就会消失,但是当我运行应用程序时,我得到一个" NoSuchMethodException"

@SuppressLint("NewApi")
public static class AnimatedTextView extends TextView {

public AnimatedTextView(Context context) {
    super(context);     
}   

public void animateHeight(int m) {        
    int maxInDp = 100;
    int maxInPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, maxInDp, getResources().getDisplayMetrics());
    ObjectAnimator objectAnimator = ObjectAnimator.ofInt(this, "barHeight", maxInPx);
    objectAnimator.setDuration(1500);
    objectAnimator.setInterpolator(new AccelerateInterpolator(1.0f));
    objectAnimator.start(); 
}

public int barHeight = 0;

public int getBarHeight() { return barHeight; }

public void setBarHeight(int height) {
    barHeight = height;
    ViewGroup.LayoutParams params = this.getLayoutParams();
    params.height = barHeight;
    this.setLayoutParams(params);
}
}

更新

想出来。为了使它工作,我将构造函数更改为

public AnimatedTextView(Context context, AttributeSet attrs) {
    super(context,attrs);
}

1 个答案:

答案 0 :(得分:1)

创建一个扩展TextView并将代码放入其中的类。然后,在您的XML中,使用:

<com.yourpackage.YourClassExtendsTextView
    android:height="match_parent"
    android:width="match_parent"/>

而不是

<TextView
    android:height="match_parent"
    android:width="match_parent"/>