Android开发Android开发Android进阶之路

数值选择器(NumberPicker)使用

2019-12-19  本文已影响0人  Lee_5566
image.png

目录

NumberPicker

数值选择器. 使用其上下旋转的方式选择数值.

默认选择数值,可以设定最大值和最小值.以及字体的颜色.

使用方式:

    <NumberPicker
        android:id="@+id/numberpicker"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:focusable="true"
        android:focusableInTouchMode="true"/>

image.png

实战

activity_main.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <NumberPicker
        android:id="@+id/numberpicker"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:focusable="true"
        android:focusableInTouchMode="true"/>

</android.support.constraint.ConstraintLayout>

代码:

package com.example.user.numberpicker;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.NumberPicker;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        NumberPicker numberPicker = findViewById(R.id.numberpicker);
        //设置最大值
        numberPicker.setMaxValue(80);
        //设置最小值
        numberPicker.setMinValue(60);
        //设置当前值
        numberPicker.setValue(65);
        //设置滑动监听
        numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            //当NunberPicker的值发生改变时,将会激发该方法
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                String toast = "oldVal:" + oldVal + "   newVal:" + newVal;
                Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

执行效果:


image.png

参考

Android NumberPicker的基本用法及常见问题汇总

上一篇 下一篇

猜你喜欢

热点阅读