Friday 2 June 2017

Kotlin :: Android Button Click Listener - Global Declaration

We will get Button action in 3 steps (Button declared as a Globally)
---------------------------------------------------------------------------

1. Create Globar variable for Button
lateinit var button : Button;

2. get Button reference from xml
button=findViewById(R.id.button) as Button;

3. set OnClickListener to Button
button.setOnClickListener(View.OnClickListener {
                   });
---------------------------------------------------------------------------
Screen Shots:
---------------------------------------------------------------------------

1. MainActivity.kt
class MainActivity : AppCompatActivity() {
    lateinit var button : Button;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button=findViewById(R.id.button) as Button;

        button.setOnClickListener(View.OnClickListener {
           Toast.makeText(applicationContext,"You Clicked  
                       Button",Toast.LENGTH_SHORT).show();
        });

    }

}
 
2.  activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="#FF00FF"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:textStyle="bold"
        android:textSize="20dp"
        android:text="Click Me"
        android:textColor="#ffffff"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
 
************************************

    Download Full Source Code HERE

************************************