Spinner containing week days, select the default day depending on the device day,
and customize background.
Demo:
Xml File:
Drawable code:<?xml version="1.0" encoding="utf-8"?> <selector
xmlns:android="http://schemas.android.com/apk/res/android"><item> <layer-list> <item> <shape android:shape="rectangle"> <corners android:radius="10dp"/> <padding android:right="10dp"/> <solid android:color=
"@color/spinner_transparent_background"/></shape> </item> <item android:drawable="@drawable/ic_drop_down" android:gravity="right|center_vertical"> </item> </layer-list> </item> </selector>
Layout code:
<Spinner
android:id="@+id/spinner"
android:background="@drawable/style_dropdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:overlapAnchor="false"
android:layout_margin="20dp" />
//
This code will show the dropdown menu below the layout
android:overlapAnchor="false"
Main File:MainActivity Code:lateinit var spinner: Spinner override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) spinner = findViewById(R.id.spinner) spinnerSet() } // Array that defines days of the week. var weekdays = arrayOf( "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ) fun getCurrentDay(): Int { val calendar = Calendar.getInstance() val day = calendar[Calendar.DAY_OF_WEEK] return when (day) { Calendar.SUNDAY -> 1 Calendar.MONDAY -> 2 Calendar.TUESDAY -> 3 Calendar.WEDNESDAY -> 4 Calendar.THURSDAY -> 5 Calendar.FRIDAY -> 6 Calendar.SATURDAY -> 0 else -> 1 } } fun spinnerSet() { val adapter = ArrayAdapter<String>( applicationContext!!, R.layout.text_spinner, weekdays ) adapter.setDropDownViewResource(R.layout.text_spinner) spinner.adapter = adapter spinner.setSelection(getCurrentDay()) spinner.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected
(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { val day = weekdays[p2] Toast.makeText(applicationContext!!,
day, Toast.LENGTH_LONG).show() } } }
No comments:
Post a Comment