The following code shows how to create a Button
and add to Activity
with code only. It also sets
up the on click listener.
package com.java2s.app; /*from ww w. j a va 2s. co 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); } }