Nat*_* K. 12 android android-widget android-layout
我还是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?
}
Run Code Online (Sandbox Code Playgroud)
我想过在自定义视图中使用这个代码但是从我看到的视图需要从ViewGroup子类化到addView方法然后再次只有absoluteLayout似乎允许设置x,y位置......我是不知如何实现这个功能.
我可能稍后会在该视图中添加一些动画,因此如果可能的话,使用SurfaceView可能会很好,但这不是必需的.
我想我找到了我试图实现的解决方案。
我创建了自己的视图子类RelativeLayout。在 onCreate() 我设置
setWillNotDraw(false);
Run Code Online (Sandbox Code Playgroud)
这样 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 );
}
Run Code Online (Sandbox Code Playgroud)
这给了我想要的结果,但是 LayoutParams 的初始化感觉(并且很可能是)错误的。有一个更好的方法吗?
| 归档时间: |
|
| 查看次数: |
5185 次 |
| 最近记录: |