简体   繁体   中英

How would I go about using an OnClickListener for a GridView of ImageButtons?

I have this GridAdapter that shows my working GridView of at least 100+ buttons, but all of these will need to navigate to a page once clicked. I'm unsure of how to begin or if what I have is a substantial place to start. I know where I'd put an OnClick method and listener but I am unsure of how to ensure every button in the grid is heard separately since they don't have Ids. Guides online have been helpful but I'm still lost. If anyone has some advice as to how to proceed I'd be grateful. Both java files are attached but the array of images is not included in the Adapter screenshot.

Grid_Adapter Grid_Fragment

You could add android:onClick="[method name here]" within the ImageButtons in your XML layout code, to call the code when each button is clicked. Note that this method has to be public and exist within the current activity.

As an example:

<?xml version="1.0" encoding="utf-8"?>
<!-- truncated -->
<Button android:id="@+id/myButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button 1"
    android:onClick="buttonClickMethod1" />
<!-- truncated -->

Also note that this isn't the preferred method, and that using onClick listeners or data bindings is a better approach.

Finally, I would question your activity layout of having 100+ buttons from a user perspective - that seems very high.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM