尝试在ViewFlipper
中切换视图时,我收到了许多工件和不正确的行为。我想添加和删除按需视图,因此,我必须调用ViewGroup.addView()
而不是使用XML。在某些时候,我想通过删除除最后一个之外的所有孩子来清理容器。这是一个演示:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
final ViewFlipper flipper = new ViewFlipper(this);
Animation in = new TranslateAnimation(-200, 0, 0, 0);
in.setDuration(300);
Animation out = new TranslateAnimation(0, 200, 0, 0);
out.setDuration(300);
flipper.setInAnimation(in);
flipper.setOutAnimation(out);
// clean it up
out.setAnimationListener(new AnimationListener(){
@Override
public void onAnimationEnd(Animation animation) {
flipper.post(new Runnable(){
public void run() {
flipper.removeViews(0, flipper.getChildCount() - 1);
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
Button button = new Button(this);
button.setText("Click me");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View a = makeView();
flipper.addView(a);
flipper.showNext();
}
});
root.addView(button);
root.addView(flipper);
setContentView(root);
}
int i = 0;
public View makeView() {
TextView tv = new TextView(MainActivity.this);
tv.setText("TextView#" + i++);
tv.setTextSize(30);
return tv;
}
}
有时我想删除所有孩子,但最后添加,以节省内存,因为这些孩子永远不会再次使用(也许我可以回收它们,但这是另一个故事)。我在动画监听器中使用通过View.post()
计划的简单runnable,并且每三次都有一些工件。
使用View.post(Runnable)
必需,因为如果您直接在动画侦听器中删除子项,则会抛出NullPointerException
,因为(至少在Honeycomb +上,它使用显示列表来绘制层次结构) )。
注意:我正在开发2.1+,因此Honeycomb动画包不适合。
答案 0 :(得分:3)
出现这些“工件”,因为在您的情况下,您尝试删除除顶部之外的所有视图,使当前显示的子项的索引无序。 ViewFlipper
将尝试补偿这一点,并且看起来不成功。但你仍然可以做你想要的,没有像这样的视觉问题:
flipper.post(new Runnable() {
public void run() {
if (flipper.getChildCount() < 4) // simulate a condition
return;
flipper.setInAnimation(null);
flipper.setOutAnimation(null);
while (flipper.getChildCount() > 1)
flipper.removeViewAt(0);
flipper.setInAnimation(in);
flipper.setOutAnimation(out);
assert flipper.getChildCount() == 1;
}
});
这应该只留下ViewFlipper
中的可见视图。看看代码是否解决了这个问题。