我正在構建一個簡單的自定義對話框,供用戶使用兩個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顯示正確的值?
感謝
PLZ標記答案權利...如果它對你來說是可行的... :) –
這是有幫助的,但它只是防止在方向變化上重新創建活動。在這個特定的場景中,我對肖像和風景都使用相同的佈局,所以我想它可以爲我工作。不過,我仍然想知道爲什麼發生這種奇怪的事情,因爲它非常令人沮喪。當然,如果沒有人會有任何其他的想法,我會標記這個答案是正確的:) – rianor
謝謝... @rianor ...從我的角度來看,..防止活動重新創建,因此數據保持相同的兩個方向手機(橫向或縱向)。 –