在 Android 中可以通过以下几种方式设置控件的颜色:
1. 在布局文件中使用 `android:background` 或 `android:textColor` 属性设置背景颜色或文字颜色:
```xml
android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FF0000" android:textColor="#00FF00" android:text="Hello, World!" /> ``` 2. 在代码中使用 `setBackgroundColor()` 或 `setTextColor()` 方法设置: ```kotlin val textView = findViewById textView.setBackgroundColor(Color.RED) textView.setTextColor(Color.GREEN) ``` 3. 使用资源文件定义颜色并引用: 在 `res/values/colors.xml` 中定义颜色: ```xml ``` 在布局文件或代码中引用: ```xml android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/colorPrimary" android:textColor="@color/colorAccent" android:text="Hello, World!" /> ``` ```kotlin val textView = findViewById textView.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary)) textView.setTextColor(ContextCompat.getColor(this, R.color.colorAccent)) ``` 4. 使用十六进制颜色码: ```kotlin val textView = findViewById textView.setBackgroundColor(0xFFFF0000.toInt()) // 红色 textView.setTextColor(0xFF00FF00.toInt()) // 绿色 ``` 总的来说,根据具体需求选择合适的方式设置控件颜色即可。使用资源文件定义颜色可以更好地管理和复用颜色,并且更易于修改。