如何使用转换来改变android studio中圆形按钮的颜色

问题描述 投票:1回答:1

我是Android工作室的一个非常基本的初学者,我正在努力为我的切换按钮添加过渡。由于它是圆形的,一旦我改变了背景颜色,它就会变成一个正方形。如果有人可以帮助我,我将非常感激。谢谢!

这是我按钮的布局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)

<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);
                }
            }
        });
    }
}
java android android-animation android-transitions
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);
© www.soinside.com 2019 - 2024. All rights reserved.