Android: View.setID(int id) programmatically - how to avoid ID conflicts?

前端 未结 15 2732
眼角桃花
眼角桃花 2020-11-21 22:53

I\'m adding TextViews programmatically in a for-loop and add them to an ArrayList.

How do I use TextView.setId(int id)? What Integer ID do I come up wit

15条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 23:38

    The 'Compat' library now also supports the generateViewId() method for API levels prior 17.

    Just make sure to use a version of the Compat library that is 27.1.0+

    For example, in your build.gradle file, put :

    implementation 'com.android.support:appcompat-v7:27.1.1

    Then you can simply use the generateViewId() from the ViewCompat class instead of the View class as follow:

    //Will assign a unique ID myView.id = ViewCompat.generateViewId()

    Happy coding !

提交回复
热议问题