如何在Android Studio中使用过渡效果更改圆形按钮的颜色

3
我是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" />

这是我用来创建圆形(roundcircle)的XML文件:

<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);
                }
            }
        });
    }
}
1个回答

0

您可以直接在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);

非常成功,非常感谢! - Damsara Perera

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接