如何在顶部设置带有文本的AppCompatRadioButton并以编程方式更改色调颜色?

时间:2017-05-17 11:38:27

标签: android android-appcompat appcompat-v7-r23

我尝试在AppCompatRadioButton顶部对齐文字并以编程方式更改setSupportButtonTintList。我成功地将文本顶部与自定义AppCompatRadioButton对齐。但是现在setSupportButtonTintList没有使用它,没有自定义setSupportButtonTintList工作正常。

acticivity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:padding="@dimen/activity_vertical_margin"
    tools:showIn="@layout/activity_main">

    <android.support.v7.widget.AppCompatRadioButton
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:button="@null"
        android:text="Top Text"
        android:drawableBottom="?android:attr/listChoiceIndicatorSingle"
        android:gravity="center" />
</RelativeLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        AppCompatRadioButton appCompatRadioButton = (AppCompatRadioButton) findViewById(R.id.radio);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int myColor = Color.parseColor("#4caf50");
            appCompatRadioButton.setSupportButtonTintList(ColorStateList.valueOf(myColor));
        }
    }
}

Screen shot

1 个答案:

答案 0 :(得分:3)

您正在为按钮应用色调,但是您已将按钮设置为xml中的null。

mappedBy

因此您无法对按钮应用色调。您正在使用drawableBottom作为单选按钮。因此,您必须将色调应用于底部的drawable。

android:button="@null"

要在drawableBottom上应用色调,您必须先获得底部可绘制然后应用色调。

android:drawableBottom="?android:attr/listChoiceIndicatorSingle"

Goodluck:)