คำอธิบายดูที่ Kotlin
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?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"></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 25 26 27 28 29 30 |
package com.phaisarns.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.widget.Button; import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // creating the button Button button = new Button(this); // setting layout_width and layout_height using layout parameters LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); button.setLayoutParams(params); button.setGravity(Gravity.CENTER_HORIZONTAL); button.setTextSize(18); button.setText("Dynamic Button"); // add Button to LinearLayout LinearLayout ll_main_layout = findViewById(R.id.ll_main_layout); ll_main_layout.addView(button); } } |
Link