Android dynamic setId to avoid duplicate IDS

Source: Internet
Author: User

Android dynamic setId to avoid duplicate IDS

When two controls with the same id are added to a layout, an error occurs when two controls with the same id are added through findVIewById.


The solution is as follows:

1. View

generateViewId()

Method to obtain an available id. Perform setId manually.

Api level 17 Required


The code of this function can be directly used below api level 17:

public static int generateViewId() {    for (;;) {        final int result = sNextGeneratedId.get();        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.        int newValue = result + 1;        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.        if (sNextGeneratedId.compareAndSet(result, newValue)) {            return result;        }    }}


2. General methods:

Samples/ApiDemos/src/com/example/android/apis/RadioGroup1.java

Samples/ApiDemp/res/values/ids. xml

Declare an id item



Set the corresponding name through setId in java code

NewRadioButton. setId (R. id. snack );




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.