【问题标题】:How to customize toggle button in android?如何在android中自定义切换按钮?
【发布时间】:2020-09-24 22:57:37
【问题描述】:

我一直在尝试自定义一个切换按钮,使其看起来像这样,但我似乎无处可去。

谁能给我一个想法或任何类型的设计教程?

【问题讨论】:

    标签: android styles customization togglebutton android-togglebutton


    【解决方案1】:

    这就是你要找的东西吗:

    首先创建一个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>
    

    【讨论】:

    • 是的!这是完美的。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2014-06-15
    • 2013-08-22
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多