Breaking News
Loading...
January 29, 2015

OnClick for Multiple Buttons on an Activity in Eclipise

Thursday, January 29, 2015

Android Eclipse - Stack Overflow - Geeky JuanJust for a short and quick tutorial today. I would just like to show how I was able to navigate through different activities using the OnClickListener. This time, instead of repetitively placing a "new OnClickListener" on every declared button, a much easier way would be is to implement it in the Activity.

First - Implement your OnClick Listener in your Activity.
public class MainActivity extends Activity implements OnClickListener {

}

Second - Implement onClick() method in the Activity
public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
      // default method for handling onClick Events..
    }

}

Third - Start implementing your OnClickListener() for your buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    Button one = (Button) findViewById(R.id.oneButton);
    one.setOnClickListener(this); // calling onClick() method
    Button two = (Button) findViewById(R.id.twoButton);
    two.setOnClickListener(this);
    Button three = (Button) findViewById(R.id.threeButton);
    three.setOnClickListener(this);

}
Fourth - Find your buttons via Id and start implementing your code on each line.
@Override
public void onClick(View v) {

    switch (v.getId()) {

    case R.id.oneButton:
        // do your code
        break;

    case R.id.twoButton:
        // do your code
        break;

    case R.id.threeButton:
        // do your code
        break;

    default:
        break;
    }

}

Through this, I was able to successfully navigate through my activities by inserting the proper code in each case in the Switch condition.

Well, the reason why I thought of posting this is because there has been a lot of misleading codes or perhaps inappropriate ones for your application. Luckily for me, this is the most simple and yet effective way I've used that shoots me out of the dilemma I faced. However, there are other ways to make things work and this could not guarantee a 100% result especially if you don't familiarize yourself with the basics.

Shoot your comments below if you have any questions. For detailed discussion please see the source given below.

Share your thoughts

0 comments:

Post a Comment

 
Toggle Footer
Web Statistics