【发布时间】:2020-09-24 22:57:37
【问题描述】:
【问题讨论】:
标签: android styles customization togglebutton android-togglebutton
【问题讨论】:
标签: android styles customization togglebutton android-togglebutton
这就是你要找的东西吗:
首先创建一个ToggleButton XML:
<ToggleButton
android:id="@+id/follow"
android:layout_width="120dp"
android:layout_height="35dp"
android:layout_centerInParent="true"
android:background="#61849f"
android:checked="false"
android:drawableStart="@drawable/ic_baseline_star_24"
android:elevation="0dp"
android:gravity="center"
android:padding="8dp"
android:textColor="#fff"
android:textOff=" FOLLOW "
android:textOn=" FOLLOWING " />
Java:
toggleButton = findViewById(R.id.follow);
toggleButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) setUnfollow();
else setFollow();
});
setFollow & setUnfollow 方法:
private void setUnfollow() {
toggleButton.setChecked(true);
toggleButton.setTextColor(Color.BLACK);
toggleButton.setBackgroundColor(Color.WHITE);
toggleButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.border));
}
private void setFollow() {
toggleButton.setChecked(false);
toggleButton.setTextColor(Color.WHITE);
toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.fill));
toggleButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_baseline_star_24, 0, 0, 0);
}
最后是fill.XML和bordre.XML(在drawable文件夹中创建这些文件)
边框.XML:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#61849f" />
</shape>
Fill.XML
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#61849f" />
</shape>
【讨论】: