Android Kotlin Button and ImageButton Example

Android Button and ImageButton represents a push button .

Android Button is a sub class of TextView .
Android ImageButton is a sub class of ImageView .

XML Layout


file : 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"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical"
        android:gravity="center">

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_label"
            android:id="@+id/button_01"/>

    <ImageButton android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:text="@string/button_label"
                 android:src="@android:drawable/ic_lock_idle_alarm"
                 android:contentDescription="@string/button_label"
                 android:id="@+id/image_button_01"/>
    
</LinearLayout>

Activity


file : MainActivity.kt

package com.tutorialsbuzz.androidbutton

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

class MainActivity : AppCompatActivity() {

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

    button_01.setOnClickListener {
      Toast.makeText(this@MainActivity, "Button Clicked ..", Toast.LENGTH_SHORT).show()
    }

    image_button_01.setOnClickListener {
      Toast.makeText(this@MainActivity, "Button Clicked ..", Toast.LENGTH_SHORT).show()
    }
}
}




No comments:

Post a comment