Rotate a button (or the text inside) in code

2019-03-29 11:12发布

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??

1条回答
ら.Afraid
2楼-- · 2019-03-29 11:48

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.

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.

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.

查看更多
登录 后发表回答