将代码变成可重用的 Class - Android

Turn code into reusable Class - Android

我正在使用以下代码来设置 TextView 的高度从 0 到 100(或在 animateHeight 方法中指定为 "m" 值的任何值)的动画。我的问题是,如何将其转换为class 这样我就可以为所有 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);
}

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

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

而不是

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