0

我有一个有趣的怪癖,我想不通。所以我将我的布局包裹在一个小部件周围,这样我就可以添加一些事件和其他方便的方法。但是,使用小部件的构造函数,我无法在 ViewPager 中将其实例化为子项。但是,如果我在没有小部件包装器的情况下膨胀布局,它就可以工作。

这是有效的代码:(不起作用的代码被注释掉)

private View getNewTabView() {
    View view = getLayoutInflater().inflate(
            R.layout.checkpoint_new_tab_view, null);

    // XmlPullParser parser = getResources().getXml(
    // R.layout.checkpoint_new_tab_view);
    // AttributeSet as = Xml.asAttributeSet(parser);
    // NewCheckpointsTabVIew view = new NewCheckpointsTabVIew(this, as);
    return view;
}

这是我的 ViewPager 的适配器代码

private class CheckpointPagerAdapter extends PagerAdapter {

    @Override
    public void destroyItem(View collection, int position, Object view) {
        ((ViewPager) collection).removeView((ScrollView) view);
    }

    @Override
    public void finishUpdate(View arg0) {
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Object instantiateItem(View arg0, int arg1) {
        View child = getNewTabView();
        ((ViewPager) arg0).addView(child, 0);
        return child;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    @Override
    public void startUpdate(View arg0) {
    }

}

下面是围绕膨胀布局的小部件的包装器:

public class NewCheckpointsTabVIew extends ScrollView {

    Context context;

    public NewCheckpointsTabVIew(Context context) {
        super(context);
        this.context = context;
    }

    public NewCheckpointsTabVIew(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    private void init() {
        // height + width
        android.view.ViewGroup.LayoutParams params = getLayoutParams();
        params.height = android.view.ViewGroup.LayoutParams.FILL_PARENT;
        params.width = android.view.ViewGroup.LayoutParams.FILL_PARENT;
        setLayoutParams(params);
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        LayoutInflater layoutInflater = (LayoutInflater) getContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.checkpoint_new_tab_view, this);
    }

    @Override
    public void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        init();
    }

}

有谁知道为什么?谢谢!

4

1 回答 1

0

解决了它,意识到我在错误的事件中膨胀它,应该在构造函数中完成。这是正确的代码: http: //pastebin.com/hYDhXxdp

于 2011-10-23T08:43:09.930 回答