android studio 如何使用 transition 改变圆形按钮的颜色

how to use transition to change the color of a circular button in android studio

我是 android studio 的初学者,我在为我的切换按钮添加过渡时遇到了很多困难。因为它是圆形的,一旦我改变背景颜色,它就会变成一个正方形。如果有人能帮助我,我将不胜感激。谢谢!

这是我的按钮布局 XML

<ToggleButton
        android:id="@+id/button2"
        android:layout_width="279dp"
        android:layout_height="279dp"
        android:layout_centerInParent="true"
        android:background="@drawable/roundcircle"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.012"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

这是我用来创建我的圈子的 XML 文件 (roundcircle)

<size android:height="283dp" android:width="283dp"/>
<solid android:color="#32CD32"/>

<corners android:radius="278dp"/>

这是 MainActivity

public class MainActivity extends AppCompatActivity {

    private ToggleButton Remote;

    private TextView Text;

    DatabaseReference database;

    TransitionDrawable transitiondrawable;

    ColorDrawable[] BackGroundColor = {
            new ColorDrawable(Color.parseColor("#ff0000")),
            new ColorDrawable(Color.parseColor("#56ff00"))
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Remote = (ToggleButton) findViewById(R.id.toggleButton);

        Button AppEffect = (Button) findViewById(R.id.button2);

        transitiondrawable = new TransitionDrawable(BackGroundColor);

        AppEffect.setBackground(transitiondrawable);

        Remote.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){

                    transitiondrawable.startTransition(3000);

                }
                else{

                    transitiondrawable.startTransition(3000);
                }
            }
        });
    }
}

你可以直接在xml中定义一个TransitionDrawable,例如button_bg.xml如下

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#ff0000"/>
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <solid android:color="#56ff00"/>
        </shape>
    </item>

</transition>

然后设置按钮的背景为button_bg.

transitiondrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.button_bg);