简体   繁体   中英

Best way to handle large number of onClick ids?

My android application is like a remote control so there is 30 buttons with 30 unique ids set like the following:

android:id="@+id/button0"
android:id="@+id/button1"
.
.
.
android:id="@+id/button29"

I want to reduce the very large switch statement I would have to make. Is there a way other than using the switch statement below to handle onClickListener for each of these buttons?

public void onClick(View v) 
{
    switch (v.getId())
    {
        case R.id.button0:
            myFunction(0);
            break;
        case R.id.button1:
            myFunction(1);
            break;
        .
        .
        .
        case R.id.button29:
            myFunction(29);
            break;

    }
}

In my ignorance I tried doing the below:

String id = Integer.toString(v.getId());
id.replace("button", "");
int buttonNum = Integer.getInteger(id);
myFunction(buttonNum);

But now I see that v.getId(); will not return button0 for example. Is it possible to get what number the button is (0-29) from the View or id in onClick ?

try to use set tag property and get value of tag(Button number) at particular button id. like

String id = Integer.toString(v.getTag());
myFunction(id);

and in XML 
 <Button
            android:id="@+id/btn1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:lineSpacingExtra="5sp"
            android:text="AAAAAA"
            android:tag="1"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

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