围绕圆圈动态排列按钮

时间:2012-02-20 21:43:55

标签: android android-layout android-widget

我还是Android的新手,所以我并不完全熟悉所有的视图组件。 我正在努力围绕一个圆圈动态对齐按钮。

我想要实现的是将n个按钮(n可以在创建时更改)添加到看起来像附加图像的视图中:

我想避免使用absoluteLayout(但我愿意接受建议,如果这是解决它的唯一方法)。 我已经想出了按钮的x / y位置的计算(暂时忽略按钮大小):

int iNumberOfButtons = 10;
double dIncrease = Math.PI * 2 / iNumberOfButtons,
    dAngle = 0,
        x = 0,
        y = 0;

  for( int i = 0; i < iNumberOfButtons; i++ )
  {
    x = 100 * Math.cos( dAngle ) + 200;
    y = 100 * Math.sin( dAngle ) + 200;
    dAngle += dIncrease;
    // get button and set position?
  }

我考虑过在自定义视图中使用此代码但是从我看到的视图需要从ViewGroup子类化以获得addView方法然后再次只有absoluteLayout似乎允许设置x,y位置......我不知道如何实现这个功能。

我稍后可能会在该视图中添加一些动画,因此如果可能的话,使用SurfaceView可能会很好,但这不是必需的。

3 个答案:

答案 0 :(得分:3)

我想我找到了我试图实现的解决方案。

我创建自己的视图子类化RelativeLayout。在onCreate()中我设置了

setWillNotDraw(false);

以便调用onDraw()。 然后我继续onDraw():

int iHeight = getHeight();
int iWidth = getWidth();
int iNumberOfButtons = 10;
double dIncrease = Math.PI * 2 / iNumberOfButtons,
       dAngle = 0,
       x = 0,
       y = 0;

  for( int i = 0; i < iNumberOfButtons; i++ )
  {
    x = 200 * Math.cos( dAngle ) + iWidth/2;
    y = 200 * Math.sin( dAngle ) + iHeight/2;
    dAngle += dIncrease;
    Button xButton = new Button(m_xContext);
    xButton.setAdjustViewBounds(true);
    xButton.setBackgroundResource(R.drawable.some_image);
    LayoutParams xParams = (RelativeLayout.LayoutParams)xButton.getLayoutParams();
    if( xParams == null )
    {
      xParams = new RelativeLayout.LayoutParams( xButton.getBackground().getIntrinsicWidth(), xButton.getBackground().getIntrinsicHeight() );
    }
    xParams.leftMargin = (int)x - ( xButton.getBackground().getIntrinsicWidth() / 2 ) ;
    xParams.topMargin =  (int)y - ( xButton.getBackground().getIntrinsicHeight() / 2 );
    addView( xButton, xParams );
  }

这给了我想要的结果,但是LayoutParams的初始化感觉(并且很可能是)错误。有更好的方法吗?

答案 1 :(得分:2)

以下Apache 2.0许可项目可以提供服务:https://github.com/dmitry-zaitsev/CircleLayout

答案 2 :(得分:0)

您可以使用RelativeLayout和子视图代替绝对布局,设置顶部和左边距。像这样:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
params.leftMargin = x;
params.topMargin = y;