Blog purpose for android basic example for android app developer. any query please my contact

Sunday, 26 July 2020

kotlin spinner example

kotlin spinner example

In this article today learn kotlin spinner example. Follow the kotlin spinner app method

var languages = arrayOf("Android", "Java", "C#", "Html", "Php", "javascipt")

 

val aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
   
// Set layout to use when the list of choices appear
   
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
   
// Set Adapter to Spinner
   
spinner!!.setAdapter(aa)

}

override fun onItemSelected(arg0: AdapterView<*>, arg1: View, position: Int, id: Long) {
   
textView_msg!!.text = "Selected : "+languages[position]
}

 

 

follow the full source code kotlin spinner example


1.MainActivity.kt:


package com.akash.koltinspinner

import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity(),AdapterView.OnItemSelectedListener {

    var languages = arrayOf("Android", "Java", "C#", "Html", "Php", "javascipt")

    var spinner:Spinner? = null
    var textView_msg:TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView_msg = this.msg

        spinner = this.spinner_sample
        spinner!!.setOnItemSelectedListener(this)

        // Create an ArrayAdapter using a simple spinner layout and languages array
        val aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
        // Set layout to use when the list of choices appear
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // Set Adapter to Spinner
        spinner!!.setAdapter(aa)

    }

    override fun onItemSelected(arg0: AdapterView<*>, arg1: View, position: Int, id: Long) {
        textView_msg!!.text = "Selected : "+languages[position]
    }

    override fun onNothingSelected(arg0: AdapterView<*>) {

    }
}


2.activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/msg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:padding="20dp"/>

    <Spinner
        android:id="@+id/spinner_sample"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

No comments:

Post a Comment