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.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.phaisarn.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating TextView programmatically TextView textView = new TextView(this); textView.setTextSize(20f); textView.setText("This is a dynamic TextView generated programmatically in Java"); // add TextView to LinearLayout LinearLayout layout = findViewById(R.id.ll_main_layout); layout.addView(textView); } } |
บรรทัดที่ 21 : ถ้างถึง LinearLayout
บรรทัดที่ 22 : เอา textView
ใส่เข้าไปใน LinearLayout