我必须像这样创建 ToggleButton
(应该在任何设备上调整大小)。
然后在ViewGroup
的onLayout
方法中进行布局。
能否请您提供一些关于如何创建它的想法?
我试过这样做:
按钮.xml
<ToggleButton
android:id="@id/add_favorites_button_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@drawable/menu_button_selector"
android:drawableTop="@drawable/star"
android:textOff=""
android:textOn=""
android:contentDescription="Add Favorites"/>
menu_button_selector.xml
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0">
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true">
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:drawable="@drawable/round_button_active"/>
</item>
<item android:state_checked="false">
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%"
android:drawable="@drawable/round_button"/>
</item>
</selector>
</item>
.....
</level-list>
round_button_active.xml
我有一些背景,只是旋转它。因为按钮应该以已知度数定位:0、45、90,...
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:topLeftRadius="50dp" android:topRightRadius="50dp"/>
<solid android:color="@color/tb_red_button"/>
<size android:width="60dp" android:height="60dp"/>
</shape>
</item>
</layer-list>
然后在 onLayout
方法中我对其进行布局:
final View button = parentLayout.getChildAt(i);
button.getBackground().setLevel(i);
button.setOnClickListener(this);
button.layout(x1, y1, x2, y2);
我收到了什么:
在 0、90、180 等角度的按钮上看起来很清楚它们应该是什么
但是
在 45、135 等角度按钮被矩形 Canvas 切割。即使我旋转它,我也是在矩形 Canvas 的范围内进行的。
最佳答案
据我了解,实现此目的的一种可能方法(使用图像)如下
将此处的图像视为半圆(两个黑色边框的半圆),它是完整圆的一部分。这个圆圈的上半部分是透明的。整个设置将是 ImageView 中的图像。
红色圆圈拇指也是与上述设置具有相同大小的图像,除了红色部分外,所有区域都是透明的。把它放在另一个 ImageView 中
现在将两个 ImageView 一个放在另一个上面,红色的在上面。将点击监听器添加到红色 ImageView 并使用 imageView.setRotate(degree)
为了提供像感觉一样的旋转运动,只需在非常短的间隔后调用上述方法并每次增加 degree 的值即可。
我添加了一张图片以便更好地理解。蓝色边框是黑色圆圈 ImageView 的边界,绿色边框是红色圆圈 ImageView 的边界。两者有一个共同的中心,所以当上面的 ImageView 旋转时,它会沿着两个黑色圆圈之间的路径给出红色圆圈的外观。
关于android - 创建 ToggleButton 的一些建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405389/