Android Dynamic SetID, avoid duplicate ID

Source: Internet
Author: User

When you add two controls with the same ID in a layout, an error occurs through Findviewbyid.


Here's how to fix it:

1. Through the view

generateViewId()

Method gets an available ID. The SetID is manually performed.

Requires API level 17


The code for the function can be used directly below API level 17:

 Public Static intGenerateviewid() {     for (;;) {        Final intresult=Snextgeneratedid.Get();        //aapt-generated IDs has the high byte nonzero, clamp to the range under that.        intNewValue=result+ 1;        if (NewValue> 0x00ffffff)NewValue= 1; //Roll over to 1, not 0.        if (Snextgeneratedid.Compareandset(result,NewValue)) {            returnresult;        }    }}


2. General Method:

Samples/apidemos/src/com/example/android/apis/radiogroup1.java

Samples/apidemp/res/values/ids.xml

Declares an ID item

<resources>
<item type= "id" name= "snack"/>
</resources>

The corresponding name is set in Java code by SetID

Newradiobutton.setid (R.id.snack);




Android Dynamic SetID, avoid duplicate ID

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.