Android Studio:如何以编程方式将 Drawable 设置为按钮文本颜色?

Android Studio : How to set a Drawable to a buttonTextColor Programatically?

如何像 XML 一样以编程方式为按钮文本颜色设置可绘制对象?

我正在创建一个服务按钮,我想在按下时更改它们的文本颜色。

方法 btn.setTextColor() 有一个整数作为表示颜色值的条目,因此当我将可绘制对象放入其中时,它被视为颜色。

private void showDialog(List list) {
    View mView = getLayoutInflater().inflate(R.layout.dialogfor_each_activity, null);
    LinearLayout ll = mView.findViewById(R.id.linearLayout);
    ll.setWeightSum((float)list.size());
    dialog.setContentView(R.layout.dialogfor_each_activity);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = (int) (displaymetrics.widthPixels * 0.90);
    int height = (int) (displaymetrics.heightPixels * 0.50);
    dialog.getWindow().setLayout(width,height);
    dialog.setCancelable(true);
    for (int i = 0; i < list.size(); i++) {
        Button btn = new Button(this);
        btn.setText(list.get(i).toString());
        btn.setTag(list.get(i).toString());
        btn.setId(i);
        btn.setBackgroundResource(R.drawable.strockbtn_white_to_roundbtn_white);
        btn.setTextColor(R.drawable.text_blue_to_white);
        btn.setTextSize(15);
        btn.setTypeface(null, Typeface.BOLD);
        btn.setPadding(0,0,0,0);
        params.setMargins(150, 6, 150, 6);
        btn.setLayoutParams(params);
        btn.setOnClickListener(this);
        ll.addView(btn);
        buttons.add(btn);
    }
    dialog.setContentView(mView);
    dialog.show();
}

我希望将 buttonTextColor 设置为 R.drawable.text_blue_to_white,就像在 XML 中一样。

EDIT : This is not a duplicate question I already done what I want in a another way.

我需要等效的 java 代码(如果可能的话):

android:textColor="@drawable/text_blue_to_white"
ContextCompat.getColor(context, R.color.yourcolor);

button.setTextColor(getResources().getColorStateList(R.color.yourcolorColor));

并为所需颜色的每个状态创建一个颜色资源

您需要在res/color/blue_to_white中拥有颜色资源:

<selector>
    <item 
        android:state_pressed="true"
        android:color="#ffffff"/>
    <item android:color="#0000ff"/>
</selector>

然后做:

btn.setTextColor(getResources().getColorStateList(R.color.blue_to_white));

编辑:重新访问 https://developer.android.com/reference/android/content/res/Resources.html#getColorStateList(int) 后,getColorStateList(int) 在 API 23 中被弃用。如果您的目标是 >= API 23,只需:

btn.setTextColor(getResources().getColorStateList(R.color.blue_to_white, getTheme()));