作者:吸毒草的秘密 | 来源:互联网 | 2023-05-18 04:25
数值选择器用于让用户输入数值,用户即可通过键盘输入数值,又可通过拖动来选择数值。该组件有如下三个常用方法:setMinValue(intminVal):设置该组件所支持的
数值选择器用于让用户输入数值,用户即可通过键盘输入数值,又可通过拖动来选择数值。
该组件有如下三个常用方法:
setMinValue(int minVal) : 设置该组件所支持的最小值。
setMaxValue(int maxVal) : 设置该组件所支持的最大值。
setValue(int value) : 设置该组件的当前值。
下面通过一个实例来介绍NumberPicker的用法。
界面效果如下所示:
布局文件如下所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:id="@+id/low_price_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="请选择低价:"/>
<NumberPicker android:id="@+id/low_number_picker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:layout_toRightOf="@id/low_price_text"/>
<TextView android:id="@+id/high_price_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/low_number_picker" android:text="请选择高价:"/>
<NumberPicker android:id="@+id/high_number_picker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/low_number_picker" android:layout_toRightOf="@id/high_price_text" android:layout_marginLeft="20dp"/>
RelativeLayout>
主程序代码如下所示:
public class NumberPickerActivity extends AppCompatActivity {
private NumberPicker lowNumberPicker,highNumberPicker;
private int minPrice=25,maxPrice=75;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_picker);
lowNumberPicker = (NumberPicker) findViewById(R.id.low_number_picker);
highNumberPicker = (NumberPicker) findViewById(R.id.high_number_picker);
lowNumberPicker.setMaxValue(10);
lowNumberPicker.setMinValue(50);
lowNumberPicker.setValue(minPrice);
lowNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
minPrice = newVal;
Toast.makeText(NumberPickerActivity.this,"您选择的最低价格为"+minPrice+",最高价格为"+maxPrice,Toast.LENGTH_SHORT).show();
}
});
highNumberPicker.setMinValue(60);
highNumberPicker.setMaxValue(100);
highNumberPicker.setValue(maxPrice);
highNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
maxPrice = newVal;
Toast.makeText(NumberPickerActivity.this,"您选择的最低价格为"+minPrice+",最高价格为"+maxPrice,Toast.LENGTH_SHORT).show();
}
});
}
}