开发者

How can I avoid duplicate ids in android child components?

I've just ventured into the fun world of Android development, but had a very quirky problem with the test app I was working on.

The app uses a TableLayout where each TableRow contains an EditText and some Buttons.

The TableRows can be added and removed at runtime. It all appeared to be working okay, until I accidentally tilted my device. The display responded and rearranged the layout, but suddenly all of the values were the same on each row.

After some head-scratching I figured out what was going on. Because of the开发者_开发问答 orientation change Android was restarting the activity. When this happens Android tries to save and then restore your instance state, but it does this by storing data relative to the component id.

In my case, because the rows are all created from the same layout, then the EditText in every row has the same id. The result as far as I can tell, is that when the info is saved it is being overwritten for each row, so that the last row wins out.

When restoring there is only one value associated with that id and so it gets applied to every row!

In my case I was able to work around it as I didn't really need to keep the values anyway. In my onSaveInstanceState I DON'T call super.onSaveInstanceState, and likewise in onRestoreInstanceState.

So that finally brings me to my question!

What if I DID want those individual row values to be saved and restored? Is there an accepted way of generating unique ids on reused components (in my case the TableRow)?


If I were you, I would not use your_view.setId(your_new_id) on an EditText view, because this makes your app less stable: What if another view happens to have the exact same Id as your_new_id?

I would use your_view.setTag(some_unique_tag) and then use findViewWithTag(some_unique_tag) to look up the EditText view again.

findViewWithTag(some_unique_tag) could be any Object - I personally prefer String because then it's easy to make some descriptive and unique tags.

Remember, it's only the Views that you use .setTag on that has tags.


In addition to setId there is a generateViewId method in the View class. If you want it pre 17 versions you can just copy it from sources.


You could generate your TableRows in Java and use View.setId(). You might also put the table row in a XML layout file, load it via java & set the Ids - but seems more tricky.

  • http://developer.android.com/reference/android/view/View.html#setId(int)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜