I am using the following code in xml to generate two RadioButtons with a divider between them:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:paddingLeft="60dp"
android:text="Male" />
<View
android:id="@+id/firstDivider"
android:layout_width="2dp"
android:layout_height="match_parent"
android:layout_marginLeft="40dp"
android:background="#939393" />
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:paddingLeft="60dp"
android:text="Female" />
</LinearLayout>
This works fine, and is being used inside a ViewPager (in one of the tabs).
Interestingly, if I scroll back and forth enough inside my ViewPager, the text on one of the buttons changes to Female. So, in the end, I get 2 Female RadioButtons.
This looks like it has something to do with View Recycling, but since they’re 2 distinctly hard coded buttons (and not ListView items, for example), I’m not sure why it’s happening.
Sure, I can add button.setText(...) in java (which hopefully will fix it), but I’ve just noticed this and I had no explanation for it.
Edit: As expected, when I do Force Close and restart the application, it switches back to normal- and I have to repeat the procedure to get two Female buttons. If I switch to another activity/etc/etc, it still stays to two “female” buttons.
The resource id for both
RadioButtonsisandroid:id="@+id/radioButton1".Android automatically saves “state” of UI elements (widgets) if created in a layout file and they have ids.
The fact that the second
RadioButtonhad the text “Female” meant it would over-write the saving of the first’s text “Male” but both would receive the same text when re-created due to the same id.