android - 以编程方式设置 textview 焦点颜色/更改主题中的焦点颜色

标签 android android-layout android-view textview

1) 是否可以通过编程方式设置 TextView 的颜色?如果是这样,最简单的方法是什么?

我想要默认 4.0+ 浅蓝色以外的其他颜色。

我发现并尝试了以下代码但没有成功:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(0x1A000000));
states.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(0x1A000000));

if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    tv.setBackgroundDrawable(states);
} else {
    tv.setBackground(states);
}

我不希望涉及任何 XML。

2) 我可以更改主题中的焦点颜色吗?如果是如何?

XML 在这里显然没问题。

最佳答案

您可以使用 ColorStateList , 以编程方式指定状态颜色。

    int[][] states = new int[][] {
        new int[] { android.R.attr.state_pressed}, // pressed
        new int[] { android.R.attr.state_focused}, // focused
        new int[] { android.R.attr.state_enabled} // enabled
    };

    int[] colors = new int[] {
        Color.parseColor("#008000"), // green
        Color.parseColor("#0000FF"), // blue
        Color.parseColor("#FF0000")  // red
    };

    ColorStateList list = new ColorStateList(states, colors);
    textView.setTextColor(list);        
    textView.setClickable(true);
    textView.setFocusableInTouchMode(true);

关于android - 以编程方式设置 textview 焦点颜色/更改主题中的焦点颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23775216/

相关文章:

android - UserRecoverableAuthException:Youtube API v3中的NeedPermission(android)

android - 键盘显示上忽略的 ScrollView 填充

android - ArrayList 为空且出现错误

android - 无法在 Android 的 XML 中设置 inflatedView 的布局宽度、高度和重量

android - 尝试使用 Robolectric 读取 Assets 时出现 FileNotFoundException

android - 跨平台 openGLES?

android - 当我从列表中选择一个项目时回来

java - Android,添加高度百分比的 View

android - 带有 Dagger 2 的 ViewModelProviders,无法掌握概念

安卓 : How to prevent users from entering numbers with more than 3 decimal places