Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can do all of them inside the same <code>listener</code>. Set all the <code>listeners</code> this way</p> <pre><code>service.setOnClickListener(this); gallery.setOnClickListener(this); </code></pre> <p>then use one function and check the <code>id</code> of the <code>View</code> that was clicked</p> <pre><code>public void onClick2 (View v) { Intent intent = new Intent(); switch (v.getId()) // get the id of the Button clicked { case (R.id.Services): intent = new Intent(Main.this, servicesActivity.class); break; case (R.id.Gallery): intent = new Intent(Main.this, galleryActivity.class); break; ... } startActivity(intent); </code></pre> <p>You can actually clean it up even more to not repeat variables with something like this</p> <pre><code>public void onClick(View v) { Intent intent = new Intent(); // create an Intent String act = null; // name for Activity to start with Intent String shield = "com.your.package."; // set package name switch (v.getId()) // get the id of the Button clicked { case (R.id.Services): act = package + "Services"; // if Services button clicked use Services as the activity break; case (R.id.Gallery): act = package + "GalleryActivity"; break; ... } try { intent = new Intent(Main.this, Class.forName(act)); // create your Intent by changing your String act to a class name startActivity(intent); // start the Intent as normal } catch (ClassNotFoundException e){ // don't forget to catch invalid class names e.printsStackTrace(); } </code></pre> <p>And as dymeh pointed out, make sure your <code>Activity</code> <code>implements OnClickListener</code></p> <p>This could probably be cleaned up a little more and may look more difficult but I use something like this in a custom menu and other places and it works nicely. It cuts down on separate functions and creating separate <code>Intents</code>. If you have to add something later or want to reuse the code it makes it a little easier, IMHO</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload