Add View programmatically, using addView() and addContentView()

This example demonstrate how to add View programmatically:

Add View Programmatically, using addView() and addContentView()
Add View Programmatically, using addView() and addContentView()

newButton ("Hello") is added to the existing layout using Layout.addView(). anotherLayout and anotherButton ("I'm another button") are added using addContentView().

package com.example.androidview;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LinearLayout mainLayout =
(LinearLayout)findViewById(R.id.mainlayout);

//newButton added to the existing layout
Button newButton = new Button(this);
newButton.setText("Hello");
mainLayout.addView(newButton);

//anotherLayout and anotherButton added
//using addContentView()
LinearLayout anotherLayout = new LinearLayout(this);
LinearLayout.LayoutParams linearLayoutParams =
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

Button anotherButton = new Button(this);
anotherButton.setText("I'm another button");
anotherLayout.addView(anotherButton);

addContentView(anotherLayout, linearLayoutParams);
}

}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#000080"
android:id="@+id/mainlayout">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textStyle="bold|italic"
android:textSize="50sp"
android:text="lesapplication.blogspot.com" />

</LinearLayout>


0 Response to "Add View programmatically, using addView() and addContentView()"

Posting Komentar