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 24 |
<?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="wrap_content" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="20sp" android:text="This is a textview generated from xml" android:textSize="20sp" /> </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 |
package com.phaisarn.ktapplication import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // creating TextView programmatically val textView = TextView(this) textView.textSize = 20f textView.text = "This is a dynamic TextView generated programmatically in Kotlin" // add TextView to LinearLayout ll_main_layout.addView(textView) } } |
บรรทัดที่ 20 : เอา textView ใส่เข้าไปใน LinearLayout