Android:在运行时在布局中沿圆圈放置视图

时间:2015-04-09 15:15:36

标签: android

我想要做的是沿中心为父布局的圆圈放置视图。

我尽我所能,我看不到任何东西。下面是我的代码。(alphabetView只是简单地从textview扩展。出于调试目的,我评论放置在圆圈上,并将其更改为沿简单线放置)

当我把它放在构造函数中时,我无法获得宽度和高度,但我可以看到子视图。据我所知,我只能在构造函数中获得0宽度和高度。所以我将代码移到了onSizeChanged。 但是现在,在将它放在onSizeChanged之后,我可以获得父布局的中心,但我看不到任何孩子。 我误解了什么吗?有没有更好的方法来实现沿环放置视图?

public class RingUIView extends RelativeLayout {
    private String[] _keySet = {"A", "B", "C", "D", "E", "F", "G"};
    private double UI_SIZE = 200;

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

        float centerX = getX() + getWidth() / 2;
        float centerY = getY() + getHeight() / 2;

        Log.e("ASDF", String.format("%f, %f", centerX, centerY));
        double radian = 0;
        for (int i = 0; i < _keySet.length; i++) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.alphabet_view, null);
            AlphabetView alphabetView = (AlphabetView) view;
            alphabetView.setText(_keySet[i]);
            this.addView(alphabetView);
            /*float childX = (float)(centerX+UI_SIZE*Math.cos(radian) - alphabetView.getWidth());
            float childY = (float)(centerY+UI_SIZE*Math.sin(radian) - alphabetView.getHeight());*/
            float childX = centerX + 20 * i;
            float childY = centerY + 20 * i;
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
            params.leftMargin = (int) childX;
            params.topMargin = (int) childY;
            radian += Math.PI / 4;
        }

    }

    public RingUIView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}

0 个答案:

没有答案