首页 > 解决方案 > Android Studio:如何以编程方式将 Drawable 设置为 buttonTextColor?

问题描述

如何像在 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();
}

我希望在 XML 中将 buttonTextColor 设置为R.drawable.text_blue_to_whitelike 。

编辑:这不是一个重复的问题,我已经以另一种方式完成了我想要的。

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

android:textColor="@drawable/text_blue_to_white"

标签: androidandroid-studioandroid-drawableandroid-buttonandroid-text-color

解决方案


您需要有一个颜色资源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()));

推荐阅读