在Asyntask中,我想更改文本切换器文本,如果我添加新视图,应用程序将崩溃。代码示例:
textSwitcher.setInAnimation(MainActivity.this,android.R.anim.slide_in_left);
textSwitcher.setOutAnimation(MainActivity.this, android.R.anim.slide_out_right);
TextView tv=new TextView(MainActivity.this);
tv.setGravity(Gravity.CENTER | Gravity.LEFT);
tv.setTypeface(custom_font);
tv.setTextColor(Color.parseColor("#00285E"));
textSwitcher.addView(tv);
在我决定删除所有视图并添加textSwitcher.removeAllViews();
之后,最后一行给出了错误,然后它给出了空指针。你认为该怎么解决?
ViewSwitcher只能有两个孩子,正如该类的文档中所说。我个人还没有见过有人使用ViewSwitcher,它是一个旧类,无论如何,你现在可以使用ObjectAnimationrs获得相同或更好的效果。
您可以创建自己的ViewGroup
,让您可以将任何视图切换为任何其他视图。如果是我,我只需要扩展FrameLayout
,然后简单地添加这样的内容:
public void switchView(View view) {
// add the new view and reveal
view.setAlpha(0);
addView(view);
view.animate().alpha(1f).start();
if (getChildCount() > 0) {
// simultaneously remove the previous view
final View child = getChildAt(0);
child.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animator) {
// remove the child when the animation ends
removeView(child);
}
}).start();
}
}
这完全是任意行为。您可以覆盖类似于ViewSwitcher
类的ViewAnimator
,并用变量子视图计数替换0/1处理。真的很简单!