如果instantiateItem使用LinearLayout和RelativeLayout,如何处理destroyItem?

时间:2013-07-08 14:59:28

标签: android android-linearlayout relativelayout

我的问题是,当调用destroyItem时,它当前会破坏LinearLayouts,但是我的instantiateItem方法实例化了相对和线性布局。因此,当调用destroyItem时,它会获得一个异常,即相对布局不能转换为线性布局。我试过if(object instanceof linearlayout)破坏那种等等......

@Override
public Object instantiateItem(View collection, int position) {

    RelativeLayout wholeView = new RelativeLayout(collection.getContext());

    // images view
    RelativeLayout images = new RelativeLayout(collection.getContext());
    for (int i = 0; i < 2; i++) {
        ImageView image = new ImageView(collection.getContext());
        image.setPadding(0, 0, 0, 0);
        images.addView(image);
        image.setImageResource(GalImages[i]);
        if (i==1) {
            image.setScaleType(ImageView.ScaleType.FIT_END);
        }
    }

    // text labels view
    LinearLayout textLabels = new LinearLayout(collection.getContext());
    textLabels.setOrientation(LinearLayout.VERTICAL);

    TextView activityDescription = new TextView(collection.getContext());
    activityDescription.setText("Warm-up");
    activityDescription.setPadding(200, 200, 0, 0);
    activityDescription.setTextSize(30);
    textLabels.addView(activityDescription);

    TextView timeLeftForThisActivity = new TextView(collection.getContext());
    timeLeftForThisActivity.setText("00:00");
    timeLeftForThisActivity.setPadding(200, 0, 0, 0);
    timeLeftForThisActivity.setTextSize(60);
    textLabels.addView(timeLeftForThisActivity);

    TextView elapsedTimeStatic = new TextView(collection.getContext());
    elapsedTimeStatic.setText("Elapsed Time: ");
    elapsedTimeStatic.setPadding(200, 0, 0, 0);
    elapsedTimeStatic.setTextSize(20);
    textLabels.addView(elapsedTimeStatic);

    // adding images and text to overall view
    wholeView.addView(images);
    wholeView.addView(textLabels);

    ((ViewPager) collection).addView(wholeView, 0);

    return wholeView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((LinearLayout) object);
}

1 个答案:

答案 0 :(得分:1)

更改cast-removeView不需要LinearLayout,它只需要一个View。 LinearLayout和RelativeLayout都来自View。