Joey Mohs Joey Mohs - 4 years ago 126
Android Question

Android: onClick causing me to go back an Activity

I am trying to build a dynamic UI, but when I add the onClick method to the button whenever I push the button I go back to my previous activity. Any ideas on how to fix it?

my button's code: (the addMenu method is never run in the activities class)

android:text="New Menu"

here is my addmenu code although no matter what goes in here(even if nothing at all) it still won't work

public void addMenu()
LinearLayout layout = (LinearLayout) findViewById(;
Button newButton = new Button(this);
newButton.setText("menu "+menu);

Answer Source

whenever I push the button I go back to my previous activity.

Sounds like your app is crashing and restarting... read the logcat, and you'd see something along the lines that your method signature is wrong.

android:onClick="addMenu" needs a method of public void addMenu(View v).

Or just use Java to set the button listener and remove android:onClick.

findViewById( View.OnClickListener() {
    public void onClick(View v) { 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download