android - 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_white
like 。
编辑:这不是一个重复的问题,我已经以另一种方式完成了我想要的。
我需要等效的java代码(如果可能的话):
android:textColor="@drawable/text_blue_to_white"
解决方案
您需要有一个颜色资源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()));
推荐阅读
- javascript - Javascript过滤器函数在生产中返回不同的结果
- android - Android - DialogFragment 不显示进入动画
- c# - 错误:ToastNotification 类型在 Windows.Foundation.UniversalApiContract 和 Windows.UI 中都存在
- c# - 在 Unity 中使用 AdMob 实现插页式广告
- python - 爆炸列
- linux - 使用 sed 查找匹配两个日期的一系列行
- c++ - Postgres自定义类型映射到C结构?
- flutter - 有没有办法在 Flutter 上找到连接速度?
- laravel - 我无法显示来自我的控制器的一些信息,我必须在 @section('content') @endsection 之间显示的信息
- php - MySQL PDO 多个 UPDATE