rianor rianor - 5 months ago 26
Android Question

Android's NumberPicker displays wrong value when screen orientation changes

I am building a simple custom Dialog for user to enter their current weight using two NumberPickers, which represents weight's integer and fractional parts. These are located side-by-side in a LinearLayout

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_horizontal">

<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/newweight"
android:layout_gravity="center_horizontal"
android:background="@color/primary_dark"/>

<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/newweightdecimal"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="1pt"
android:background="@color/primary_dark"/>
</LinearLayout>


I have noticed that after screen orientation changes and the activity is recreated, the first NumberPicker always displays the whatever number the second one shows.

Weird part is, that when it's value is accessed programmatically, it returns the correct one. Furthermore selecting + or - on the numberpicker (going up or down the list) gets the NumberPicker to display the correct value again.

For example if before the orientation change first one displays 70 and second one displays 1, afterwards both shows 1. However its getValue returns 70. Also if I select + on the first number picker, it changes its value to 71, as you would expect if it shows 70 in the first place.

Here is the initialization of both NumberPickers in Activity's onCreate method.

NumberPicker newweight = (NumberPicker) findViewById(R.id.newweight);
newweight.setMinValue(0);
newweight.setMaxValue(250);
newweight.setValue((int)Math.round( Math.floor(weight) ));
newweight.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

NumberPicker newweightdecimal = (NumberPicker) findViewById(R.id.newweightdecimal);
newweightdecimal.setMinValue(0);
newweightdecimal.setMaxValue(9);
newweightdecimal.setValue((int)Math.round( 10*(weight - Math.floor(weight))) );
newweightdecimal.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);


Does anyone have an idea on why this is happening and how to make sure the NumberPicker displays the correct value?

Thanks

Answer

Use these code in the yours manifest file(in the yours activity class) than data will not change in the both mode of the mobile(landscape or portrait)

android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode

OR USE SIMPLY THESE

android:configChanges="orientation|screenSize|screenLayout"
Comments