Skip to main content

Posts

Showing posts with the label button

android kotlin - Button with icon

MainActivity.kt package com.example.jetpack import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // get drawable from resource val drawable = ContextCompat.getDrawable( applicationContext,R.drawable.ic_check ) // programmatically set the second button left drawable / icon button2.setCompoundDrawablesWithIntrinsicBounds( drawable, // left null, // top null, // right null // bottom ) } } activity_main.xml <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://sc...

Android Kotlin: How to implement Button click listener

Android Kotlin - Implementing Button Click Listeners This code demonstrates various ways to implement click listeners for buttons in an Android application written with Kotlin. The code includes a MainActivity class and the corresponding layout file activity_main.xml . MainActivity.kt Breakdown: Imports: The code starts by importing necessary libraries like View , TextView , Button , and AppCompatActivity . Activity Class: The MainActivity class inherits from AppCompatActivity , which is the base class for most activities in Android. onCreate Method: This method is called when the activity is first created. It performs the following: Sets the layout using setContentView(R.layout.activity_main) . Finds the UI elements (TextView and Buttons) using findViewById . Initializes a counter variable to keep track of button clicks. Setting Click Listeners: The code demonstrates four ways to set click listeners for different buttons: Using a lambda expression: This is the most co...