将ArrayList条目设置为ViewFlipper子女
问题描述:
我的活动中显示了30多个视图。每一个都是一个带有嵌套ImageView和一些TextView的RelativeLayout(其中一些是静态的,其中一些是可变的)。重构来显示结果,它看起来像的编程方式:将ArrayList条目设置为ViewFlipper子女
tbnImages = db.getTbnImages();
tbnNames = db.getTbnNames();
tbnExts = db.getTbnExts();
tbnDescs = db.getTbnDescs();
vf = (ViewFlipper) findViewById(R.id.viewFlipperTbnImages);
vf.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.left_in));
vf.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.left_out));
detector = new SimpleGestureFilter(this, this);
tbnImage = (ImageView) findViewById(R.id.tbnImage);
tbnName = (TextView) findViewById(R.id.tbnName);
tbnExt = (TextView) findViewById(R.id.tbnExt);
tbnDesc = (TextView) findViewById(R.id.tbnDesc);
我应该如何配置我的ViewFlipper这样,当在最后一个视图推法(.showNext()
重定向到.showNext()
和.showPrevious()
方法会显示正确的意见,包括正确的行为第一个视图)和第一个(.showPrevious()
提供最后一个视图)?
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
vf.showPrevious();
break;
case SimpleGestureFilter.SWIPE_LEFT:
vf.showNext();
break;
}
所有变量(ImageView图片和TextView文本)取自ArrayList。如何将它们设置为ViewFlipper子项?
答
您需要生成所有30个视图并将它们添加为ViewFlipper的子视图。如果所有视图都共享一个布局,则应该创建一个自定义视图来处理它。
public class CustomView extends RelativeLayout{
public CustomView(Context context, Uri imageUri, String tbnName, String tbnDescripton, String tbnDesc) {
super(context);
LayoutInflater.from(context).inflate(R.layout.your_layout_resource, this, true);
ImageView tbnImage = (ImageView) findViewById(R.id.tbnImage);
TextView tbnName = (TextView) findViewById(R.id.tbnName);
TextView tbnExt = (TextView) findViewById(R.id.tbnExt);
TextView tbnDesc = (TextView) findViewById(R.id.tbnDesc);
tbnImage.setImageURI(imageUri);
tbnName.setText(tbnName);
tbnImage.setText(tbnDescription);
tbnExt.setText(tbnDesc);
}
}
其中'your_layout_resource'是您当前使用'merge'元素作为根的RelativeLayout资源。然后,你只需要创建你需要的所有意见,并把它们添加到您的ViewFlipper:
for(int i = 0; i<tbnImages.size(); i++){
vf.addView(new CustomView(context,
tbnImages.get(i),
tbnNames.get(i),
tbnDescripton.get(i),
tbnDescs.get(i)));
}
总之,30次有很多的意见。你确定ViewPager不适合你吗?
工作完美,谢谢! 关于ViewPager:我想将其添加到我的未来项目之一,所以当我更熟悉时,也许我会重构代码。感谢提及,我几乎忘了这个布局管理器:-) – AbreQueVoy