Skip to content

Instantly share code, notes, and snippets.

@akexorcist
Created July 9, 2016 09:47
Show Gist options
  • Select an option

  • Save akexorcist/4edbaf42cc7d8b15a86cec39c678e544 to your computer and use it in GitHub Desktop.

Select an option

Save akexorcist/4edbaf42cc7d8b15a86cec39c678e544 to your computer and use it in GitHub Desktop.
วิธีการเพิ่ม View ตัวอื่นๆเข้าไปแบบ Programmatically (ใช้โค้ด Java)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.akexorcist.myapplication.MainActivity">
<Button
android:id="@+id/btn_add_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add View" />
</LinearLayout>
package com.akexorcist.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout layoutRoot;
private Button btnAddView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutRoot = (LinearLayout) findViewById(R.id.layout_root);
btnAddView = (Button) findViewById(R.id.btn_add_view);
btnAddView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO When user click this button
addNewView();
}
});
}
public void addNewView() {
View view = LayoutInflater.from(this).inflate(R.layout.view_simple_button, null);
layoutRoot.addView(view);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_stupid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stupid Button" />
</LinearLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment