数值选择器的功能及用法
数值选择器用于让用户选择自己需要的数值,既可以通过手动输入的形式,也可以通过拖动的方式,使用该组件常用如下三个方法:
1.setMinValue(int minVal):设置该组件支持的最小值。
2.setMaxValue(int maxVal):设置该组件支持的最大值。
3.setValue(int value):设置该组件的当前值。
实例:选择意向的价格范围
运行图:
在layout下的activity_main下:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main3Activity">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="选择最低价:"
android:textSize="24dp"
android:layout_width="120dp"
android:padding="10dp"
android:layout_height="wrap_content"/>
<NumberPicker
android:id="@+id/np1"
android:layout_width="match_parent"
android:layout_height="80dp"
android:focusable="true"
android:focusableInTouchMode="true"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="选择最高价:"
android:textSize="24dp"
android:layout_width="120dp"
android:padding="10dp"
android:layout_height="wrap_content"/>
<NumberPicker
android:id="@+id/np2"
android:layout_width="match_parent"
android:layout_height="80dp"
android:focusable="true"
android:focusableInTouchMode="true"/>
</TableRow>
</TableLayout>
在MainActivity.java下:
package com.example.test04;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.NumberPicker;
import android.widget.Toast;
public class Main3Activity extends AppCompatActivity {
// 定义最低价最高价的初始值
private int min=25;
private int max=75;
private NumberPicker np1;
private NumberPicker np2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
np1=findViewById(R.id.np1);
np2=findViewById(R.id.np2);
// 设置np1的最大值和最小值
np1.setMinValue(0);
np1.setMaxValue(50);
// 设置np1的当前值
np1.setValue(min);
np1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 当np1值改变后,会触发该方法
min=newVal;
Selected();
}
});
// 设置np2的最大值和最小值
np2.setMinValue(50);
np2.setMaxValue(100);
// 设置np2的初始值
np2.setValue(max);
np2.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 当np2的值改变后,会触发该方法
max=newVal;
Selected();
}
});
}
private void Selected() {
Toast.makeText(this, "最低价格为:"+min+",最高价格为:"+max, Toast.LENGTH_SHORT).show();
}
}
如果你喜欢的话,关注加点赞哦!!!