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)

<Button
android:text="New Menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/newButton"
android:layout_weight="1"
android:onClick="addMenu"/>


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(R.id.backLayer);
Button newButton = new Button(this);
newButton.setText("menu "+menu);
layout.addView(newButton);
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(R.id.newButton).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) { 
        addMenu();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download