Material button change color Example
Kotlin là một ngôn ngữ lập trình kiểu tĩnh chạy trên máy ảo Java và có thể được biên dịch sang mã nguồn Java hay sử dụng cơ sở hạ tầng trình biên dịch LLVM. Nó được tài trợ và phát triển bởi bởi JetBrains.
Create class MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// material button background color programmatically
buttonClick.setOnClickListener {
(it as MaterialButton).apply {
// set material button background tint list as a single color
backgroundTintList = ColorStateList.valueOf(Color.YELLOW)
// set material button background tint mode
backgroundTintMode = PorterDuff.Mode.SRC_ATOP
}
}
}
}
Create layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/constraintLayout"
tools:context=".MainActivity">
<com.google.android.material.button.MaterialButton
android:id="@+id/buttonNormal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Material Button Normal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.button.MaterialButton
android:id="@+id/buttonTint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:backgroundTint="#D3212D"
android:text="Material Button Background Red"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/buttonNormal" />
<com.google.android.material.button.MaterialButton
android:id="@+id/buttonTintMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:backgroundTint="#D3212D"
android:backgroundTintMode="multiply"
android:text="Tint Red + Mode Multiply"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/buttonTint" />
<com.google.android.material.button.MaterialButton
android:id="@+id/buttonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Click To Change Background"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/buttonTintMode" />
</androidx.constraintlayout.widget.ConstraintLayout>
Kết Quả:
Post a Comment
Post a Comment