如何在Android Studio中修改应用文字与背景颜色?
修改Android应用文字与背景颜色的方法
通过XML布局文件修改(推荐)
默认Empty Activity的布局文件是res/layout/activity_main.xml,可直接在这里调整颜色:
- 修改文字颜色:找到
<TextView>标签,添加或修改android:textColor属性,比如设置白色文字:<TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello Android!" android:textColor="#FFFFFF" <!-- 白色 --> app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> - 修改背景颜色:若要改整个页面背景,给根布局(如
ConstraintLayout)添加android:background属性;若仅修改文字区域背景,给TextView添加该属性:<!-- 根布局设为白色背景 --> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" <!-- 白色背景 --> tools:context=".MainActivity"> <!-- TextView 代码 --> </androidx.constraintlayout.widget.ConstraintLayout>
通过Kotlin代码修改
在MainActivity.kt的onCreate方法中,获取控件实例后动态设置颜色:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val textView = findViewById<TextView>(R.id.textView) // 设置文字为白色 textView.setTextColor(Color.WHITE) // 设置TextView背景为黑色 textView.setBackgroundColor(Color.BLACK) // 若要设置整个页面背景,先给根布局添加id(比如root_layout),再执行: // findViewById<ConstraintLayout>(R.id.root_layout).setBackgroundColor(Color.WHITE) }
注:如果根布局没有id,需先在activity_main.xml的根布局标签里添加android:id="@+id/root_layout"。
内容的提问来源于stack exchange,提问作者Bob Walance




