首页 > 解决方案 > 以编程方式在android中更改textview颜色的新方法是什么

问题描述

XML

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
app:titleTextColor="#ffffff"
>
<TextView
    android:id="@+id/name"
    android:layout_width="275dp"
    android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>

活动

公共类聊天扩展 AppCompatActivity {

private TextView name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);

    name = (TextView) findViewById(R.id.name);

    TextView textView = new TextView(R.layout.activity_chat);
    name.setText((getIntent().getStringExtra("Recievers_Name")));
    name.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));

我试过了

name.setTextColor(getResources().getColor(R.color.white));

  name.setTextColor(color.WHITE);

  name.setTextColor(Color.parseColor("#FFFFFF"));

但无法正常工作......请帮助...................................... .....................

标签: javaandroidxmltextcolors

解决方案


试试这个方法,它在所有 Api 级别上都可以正常工作。

public int _getColor(int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 23) {
        return ContextCompat.getColor(this, id);
    } else {
        return getResources().getColor(id);
    }
}

推荐阅读