如何在自定义ViewGroup中膨胀RelativeLayout

时间:2011-06-18 08:07:09

标签: android android-layout relativelayout viewgroup android-inflate

我有一个自定义动画ViewGroup(主要基于SlidingTab)。

在我的应用程序中,我将其删除为仅一个TextView,其行为就像SlidingTab(锁定屏幕上的滑块)。这很好用,但幻灯片的TextView是在代码中定义的。我希望有一个完整的RelativeLayout可以滑动。

我查看过各种各样的帖子trying different things,但仍然没有让它发挥作用。 RelativeLayout xml文件必须在Slider构造函数中作为“父”的子项进行膨胀和添加,但我还需要能够执行measure()和layout()方法。请参阅下面的相关代码。

公共类SlindingView扩展了ViewGroup {

private static Slider mLeftSlider;
private static int tabWidth;

/**
 * Simple container class for all things pertinent to a slider.
 */
private static class Slider {

    private final TextView tab;

    Slider(ViewGroup parent) {
        // Want to change 'tab' to a RelativeLayout in xml
        tab = new TextView(parent.getContext());
        tab.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.FILL_PARENT));
        tab.setText("SLIDE THIS");

        parent.addView(tab);
    }

    void layout(int l, int t, int r, int b) {
        tabWidth = getTabWidth();
        int tabHeight = getTabHeight();
        tab.layout(0, 0, tabWidth, tabHeight);
    }

    public void measure() {
        tab.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    }

    public int getTabWidth() {
        return tab.getMeasuredWidth();
    }

    public int getTabHeight() {
        return tab.getMeasuredHeight();
    }
}

/**
 * Constructor
 */
public SlindingView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mLeftSlider = new Slider(this);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);

    mLeftSlider.measure();
    final int leftTabWidth = mLeftSlider.getTabWidth();
    final int leftTabHeight = mLeftSlider.getTabHeight();
    final int width = Math.max(widthSpecSize, leftTabWidth);
    final int height = leftTabHeight;

    setMeasuredDimension(width, height);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    mLeftSlider.layout(l, t, r, b);
}

}

0 个答案:

没有答案