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

前端 未结 15 2486
眼角桃花
眼角桃花 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:41

    My Choice:

    // Method that could us an unique id
    
        int getUniqueId(){
            return (int)    
                    SystemClock.currentThreadTimeMillis();    
        }
    
    0 讨论(0)
  • 2020-11-21 23:47

    (This was a comment to dilettante's answer but it got too long...hehe)

    Of course a static is not needed here. You could use SharedPreferences to save, instead of static. Either way, the reason is to save the current progress so that its not too slow for complicated layouts. Because, in fact, after its used once, it will be rather fast later. However, I dont feel this is a good way to do it because if you have to rebuild your screen again (say onCreate gets called again), then you probably want to start over from the beginning anyhow, eliminating the need for static. Therefore, just make it an instance variable instead of static.

    Here is a smaller version that runs a bit faster and might be easier to read:

    int fID = 0;
    
    public int findUnusedId() {
        while( findViewById(++fID) != null );
        return fID;
    }
    

    This above function should be sufficient. Because, as far as I can tell, android-generated IDs are in the billions, so this will probably return 1 the first time and always be quite fast. Because, it wont actually be looping past the used IDs to find an unused one. However, the loop is there should it actually find a used ID.

    However, if you still want the progress saved between subsequent recreations of your app, and want to avoid using static. Here is the SharedPreferences version:

    SharedPreferences sp = getSharedPreferences("your_pref_name", MODE_PRIVATE);
    
    public int findUnusedId() {
        int fID = sp.getInt("find_unused_id", 0);
        while( findViewById(++fID) != null );
        SharedPreferences.Editor spe = sp.edit();
        spe.putInt("find_unused_id", fID);
        spe.commit();
        return fID;
    }
    

    This answer to a similar question should tell you everything you need to know about IDs with android: https://stackoverflow.com/a/13241629/693927

    EDIT/FIX: Just realized I totally goofed up the save. I must have been drunk.

    0 讨论(0)
  • 2020-11-21 23:49

    You can set ID's you'll use later in R.id class using an xml resource file, and let Android SDK give them unique values during compile time.

     res/values/ids.xml
    

    <item name="my_edit_text_1" type="id"/>
    <item name="my_button_1" type="id"/>
    <item name="my_time_picker_1" type="id"/>
    

    To use it in the code:

    myEditTextView.setId(R.id.my_edit_text_1);
    
    0 讨论(0)
提交回复
热议问题