1

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

在我的应用程序中,我将其简化为一个 TextView,其行为类似于 SlidingTab(锁定屏幕上的滑块)。这很好用,但是滑动的 TextView 是在代码中定义的。我想要一个可以滑动的整个 RelativeLayout。

我查看了各种尝试不同事物的帖子,但仍然没有让它发挥作用。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);
}

}

4

0 回答 0