Adding Components to Activity We have two options: 1- Creating a xml layout file with button in it. 2- Adding button dynamically to your Activity.
1- Creating a xml layout file with button in it. <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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TableLayout" android:id="@+id/button" /> </LinearLayout> and use this layout in your Activity: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button myTableButton=(Button) findViewById(R.id.button); myTableButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d("Hi", "hi"); } });
2- Adding button dynamically to your Activity. <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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TableLayout" android:id="@+id/button" /> <LinearLayout android:id="@+id/layout1" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"></LinearLayout> </LinearLayout> *******************************Add this to your main activity. LinearLayout layout = (LinearLayout) findViewById(R.id.layout1); layout.setOrientation(LinearLayout.HORIZONTAL); Button myNew; myNew = new Button(this); myNew.setText("Hi"); layout.addView(myNew); myNew.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("First","Log"); } }); Button btn = new Button(this); btn.setText("OK1"); layout.addView(btn); ...