Create Button with code only

Description

The following code shows how to create a Button and add to Activity with code only. It also sets up the on click listener.

Example


package com.java2s.app;
//from w  w w  . ja v a  2s .  c o m
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout parentContainer = new LinearLayout(this);
        parentContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        parentContainer.setOrientation(LinearLayout.VERTICAL);

        Button button = new Button(this);
        button.setText("OK");
        parentContainer.addView(button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v("java2s.com","button clicked");
            }
        });

        setContentView(parentContainer);
    }
}
Create Button with code only




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView