Android的NumberPicker在屏幕方向更改时显示错误值
我正在构建一个简单的自定义对话框,供用户使用两个NumberPickers(它们表示权重的整数和小数部分)输入其当前权重。这些位于并排侧在LinearLayout中Android的NumberPicker在屏幕方向更改时显示错误值
<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>
我注意到,屏幕方向的变化和活性重建后,第一NumberPicker始终显示任何数字,第二个节目。
奇怪的是,当它的值以编程方式访问时,它会返回正确的值。此外,在numberpicker(向上或向下列表)上选择+或 - 可使NumberPicker再次显示正确的值。
例如,如果在方向改变之前第一个显示70,第二个显示1,之后两者都显示1.然而,它的getValue返回70.同样,如果我在第一个数字选择器上选择+,它将其值更改为71,正如你所期望的那样,如果它首先显示70。
以下是Activity的onCreate方法中两个NumberPickers的初始化。
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);
有没有人有一个想法,为什么发生这种情况,以及如何确保NumberPicker显示正确的值?
感谢
使用在你的这些代码清单文件(在你的活动课)比数据将不会在移动(横向或纵向)
android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode
的两个模式改变或使用只需将这些
android:configChanges="orientation|screenSize|screenLayout"
一旦屏幕方向是变化的活动被重建使存储的onPause方法你的电话号码采摘值。 并在onSaveInstance中抓取该值并重新设置为号码选取器。
我可能应该提到,但我已经这样做了。而且它没有显示从onCreate方法分配的值。无论该值是否从创建时间开始改变,左侧选取器始终会在方向更改后显示与右侧选取器相同的编号。最重要的是,它没有显示出它自己的价值 – rianor
我知道这对你来说可能已经太晚了,但它可能会帮助其他人。
NumberPicker似乎包含正确的值,但显示错误的值。 (我使用Theme.Black NumberPicker样式)
我还没有找到刷新/重绘/重绘的方法,所以我将该值设置为0,然后再次将其设置为我想要的值onRestoreInstanceState( )(在onCreate()中不起作用,它是一个额外的初始化)。
添加以下onRestoreInstanceState(捆绑):
NumberPicker newweight = (NumberPicker) findViewById(R.id.newweight);
newweight.setValue(0);
newweight.setValue((int)Math.round(Math.floor(weight)));
NumberPicker newweightdecimal = (NumberPicker) findViewById(R.id.newweightdecimal);
newweightdecimal.setValue(0);
newweightdecimal.setValue((int)Math.round(10*(weight - Math.floor(weight))));
为避免重复,你可以把这个功能和从的onCreate和onRestoreInstanceState称之为()。
我这样做的所有NumberPickers,它似乎是我可以接受的解决方法。
PLZ标记答案权利...如果它对你来说是可行的... :) –
这是有帮助的,但它只是防止在方向变化上重新创建活动。在这个特定的场景中,我对肖像和风景都使用相同的布局,所以我想它可以为我工作。不过,我仍然想知道为什么发生这种奇怪的事情,因为它非常令人沮丧。当然,如果没有人会有任何其他的想法,我会标记这个答案是正确的:) – rianor
谢谢... @rianor ...从我的角度来看,..防止活动重新创建,因此数据保持相同的两个方向手机(横向或纵向)。 –