Skip to content Skip to sidebar Skip to footer

Android Button Navigation With Onclick Listeners

main.xml -------- |button1| (button press)>page1.xml |button2| (button press)>page2.xml |button3| (button press)>page3.xml |button4| (button press)>page4.xml |button5|

Solution 1:

You should define one activity for each of the pages. So totally 7 activities including the main. In main activity, define single onClickListener to handle all clicks.

classClickListenerimplementsView.OnClickListener {
    voidonClick(View v) {
       switch(v.getId()) {
        case R.id.btn_1:
             ...
             break;
        ...
       }
    }

Set this listener to all your 6 buttons.

Solution 2:

You are definitely doing this all wrong. All of your buttons are calling the same activity. If you want them to go different places, create different activities. If you want them to go the the same place with different data, use the intent to send the information as an extra.

Also, just for readability, you may want to learn about XML defined on-click methods.

Solution 3:

Ok, first off, implement the OnClickListener, you'll have to add the unemplemented method onClick()

publicclassActivity1extendsActivityimplementsOnClickListener {

Then initialize your buttons and add click listeners to them in your onCreate()

Button1 = (Button) findViewById(R.id.autobody);
Button1.setOnClickListener(this);

Then in onClick() set up a switch/case

@OverridepublicvoidonClick(View v) {
    // TODO Auto-generated method stubswitch (v.getId()) {
    case R.id.autobody:
        // do codebreak;
    case R.id.glass:
        // do codebreak;
    }
}

I just did a few of your buttons, but you can figure out the rest. Just make sure to initialize and add the onClickListeners to them all in onCreate()

Solution 4:

Do not use buttons for this functionality. Use a ListView and with its onItemClickListener you will get the number of the row that is clicked. You can then use ViewPager to show pages based on the click.

Solution 5:

  1. Change your OnClick methods with a single switch-case
  2. Pass data from the activity1 like this:

    intent.putExtra("buttonClick", buttonnumber); startActivity(intent);

  3. Receive the data in activity2 like this:

    clickedButton = getIntent().getExtras().getString("buttonClick");

  4. Change the method name to OnCreate in activity2

Post a Comment for "Android Button Navigation With Onclick Listeners"