先設定一個範圍,
然後讓使用者來挑選一個數值。
這個實作方法很簡單,先設定最大最小的範圍,還有一開始的預設值
numPicker.setMaxValue(50);
numPicker.setMinValue(0);
numPicker.setValue(10);
接著利用setOnValueChangedListener來監看使用者選擇的值int oldValue表示調整前的值
int newValue表示調整後的值
numPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener (){
public void onValueChange(NumberPicker view, int oldValue, int newValue) {
tv.setText("pick number is " + String.valueOf(newValue));
}
});
完整source code如下
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.widget.NumberPicker;
import android.widget.TextView;
public class MainActivity extends Activity {
public NumberPicker numPicker;
public TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
numPicker=(NumberPicker) findViewById(R.id.numberPicker1);
numPicker.setMaxValue(50);
numPicker.setMinValue(0);
numPicker.setValue(10);
//取得使用者選擇的值
numPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener (){
public void onValueChange(NumberPicker view, int oldValue, int newValue) {
tv.setText("pick number is " + String.valueOf(newValue));
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:text="pick number is 10"
android:textAppearance="?android:attr/textAppearanceLarge" />
<NumberPicker
android:id="@+id/numberPicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp" />
</RelativeLayout>
結果android 4.1跑出來NumberPicker是長這樣

你好,我有用alertdialog,但是裡面的NumberPicker 卻不會出現設定好的最大值與最小值
回覆刪除