我编写了一个代码,使用TextView
和Animator
显示了一个字符串数组。
有一个更好的方法吗?这是我的代码:
class TextViewAnimator {
private TextView textView;
private String[] strings;
private boolean autoRemove;
private int pos = 0;
TextViewAnimator(TextView textView, String[] strings,boolean autoRemove) {
this.textView = textView;
this.strings = strings;
this.autoRemove = autoRemove;
}
void startAnimation() {
if(pos < strings.length) {
textView.setText(strings[pos]);
textView.animate().alpha(1.0f).setDuration(700).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textView.animate().alpha(0.0f).setStartDelay(700).setDuration(700).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
pos++;
startAnimation();
}
});
}
});
}
else {
if(autoRemove) ((ViewGroup)textView.getParent()).removeView(textView);
}
}
}
答案 0 :(得分:0)
这可能是更具可读性的代码。
JAVA
class TextViewAnimator extends AnimatorListenerAdapter {
private TextView textView;
private String[] strings;
private Boolean autoRemove;
private int pos = 0;
TextViewAnimator(TextView textView, String[] strings,boolean autoRemove) {
this.textView = textView;
this.strings = strings;
this.autoRemove = autoRemove;
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if (textView.getAlpha() == 1.0f) {
animateLine(textView, 0.0f);
}
if (textView.getAlpha() == 0.0f) {
pos++;
startAnimation();
}
}
private void animateLine(TextView textview, Float alpha) {
textview.animate()
.alpha(alpha)
.setStartDelay(700)
.setDuration(700)
.setListener(this);
}
private void startAnimation() {
if (pos < strings.length) {
textView.setText(strings[pos]);
animateLine(textView, 1.0f);
} else {
if (autoRemove) ((ViewGroup) textView.getParent()).removeView(textView);
}
}
}
科特琳
class TextViewAnimator(private val textView: TextView,
private val strings: Array<String>,
private val autoRemove: Boolean) : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
if (textView.alpha == 1.0f) {
textView.animateLine(0.0f)
}
if (textView.alpha == 0.0f) {
pos++
startAnimation()
}
}
private fun TextView.animateLine(alpha: Float) {
animate()
.alpha(alpha)
.setStartDelay(700)
.setDuration(700)
.setListener(this@TextViewAnimator)
}
private var pos = 0
private fun startAnimation() {
if (pos < strings.size) {
textView.text = strings[pos]
textView.animateLine(1.0f)
} else {
if (autoRemove) (textView.parent as ViewGroup).removeView(textView)
}
}
}