activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <LinearLayout android:id="@+id/ll_main_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" /> </LinearLayout> </android.support.constraint.ConstraintLayout> |
MainActivity.kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout 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) // get reference to button val button1: Button = findViewById(R.id.button1) // set on-click listener button1.setOnClickListener { // your code to perform when the user clicks on the button Toast.makeText(this@MainActivity, "You clicked me.", Toast.LENGTH_SHORT).show() } // creating the button val button2 = Button(this) // setting layout_width and layout_height using layout parameters button2.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) button2.text = "Dynamic Button" button2.setOnClickListener { Toast.makeText(this, "Dynamic Button", Toast.LENGTH_SHORT).show() } // add Button to LinearLayout ll_main_layout.addView(button2) } } |