ทุกครั้งที่กดปุ่ม ก็จะสลับ Background
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/btn_center_gradient" android:padding="15dp" android:text="Changing Button" android:textColor="#FFFFFF" /> </LinearLayout> </android.support.constraint.ConstraintLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var button_background: Int = 1 button.setOnClickListener { if (button_background == 2) { button.setBackgroundResource(R.drawable.btn_center_gradient) button_background = 1; } else if (button_background == 1) { button.setBackgroundResource(R.drawable.btn_oval_gradient) button_background = 2; } } } } |
drawable/btn_center_gradient.xml
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:centerColor="#12434c" android:endColor="#258191" android:startColor="#44e3ff" /> </shape> |
drawable/btn_oval_gradient.xml
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <gradient android:angle="90" android:centerColor="#7a5d28" android:endColor="#ad853a" android:startColor="#ffc456" /> </shape> |