问题描述
我必须通过编码随机旋转一个按钮(或其中的文本,相同)。 API级别低于11的按钮是否有任何button.setRotate(x)?
I have to rotate a button (or the text inside, it's the same) by random degree by coding. Is there any button.setRotate(x) in API level lower then 11??
推荐答案
好,看看答案是:很复杂。
Ok, had a look and the answer is: It's complicated.
您可以使用旧的动画框架旋转按钮,例如像这样:
You can rotate the button using the old animation framework, e.g. like this:
Button button = (Button) findViewById(R.id.button);
// rotation from 0 to 90 degrees here
RotateAnimation a = new RotateAnimation(0, 90);
a.setFillAfter(true);
a.setDuration(0);
button.startAnimation(a);
这里的问题是按钮看上去旋转了,但无法正确单击。触发点击事件的坐标是在旋转之前按钮在按钮所在区域的坐标。
The problem here is that the button looks rotated, but can't be clicked correctly. The coordinates that trigger the click event are the ones at the area the button had before beeing rotated.
由于这不是一个很好的解决方案,因此最好的选择是在 onDraw()
中编写一个扩展Button类并旋转按钮画布的自定义视图。在这种情况下,您还必须覆盖 onMeasure()
。有关执行操作的说明,请参见。
Since this is not a very good solution, your best bet is probably to write a custom view that extends the Button class and rotate the buttons canvas in onDraw()
. You also have to override onMeasure()
in this case. See Custom Components for a introduction what to do.
除此之外,您可以尝试从按钮父级布局中拦截单击事件,并在按钮当前坐标内发生单击时触发适当的事件。不过,这有点 hacky。
Apart from that you can try to intercept click events from the buttons parent layout and trigger the appropriate event when the click happened within the buttons current coordinates. This is somewhat "hacky" though.
这篇关于旋转代码中的按钮(或其中的文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!