首页
/ 【亲测免费】 NumberPicker 开源项目使用教程

【亲测免费】 NumberPicker 开源项目使用教程

2026-01-19 10:18:18作者:伍希望

项目介绍

NumberPicker 是一个用于选择数字的自定义控件,支持整数和小数的选择。该项目在 GitHub 上开源,地址为:https://github.com/ShawnLin013/NumberPicker。NumberPicker 提供了丰富的自定义选项,如字体大小、颜色、分割线颜色等,使得开发者可以轻松地集成到自己的应用中。

项目快速启动

1. 添加依赖

首先,在项目的 build.gradle 文件中添加以下依赖:

dependencies {
    implementation 'com.github.ShawnLin013:NumberPicker:2.4.12'
}

2. 在布局文件中使用 NumberPicker

res/layout 目录下的 XML 文件中添加 NumberPicker 控件:

<com.shawnlin.numberpicker.NumberPicker
    android:id="@+id/number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:np_width="64dp"
    app:np_height="180dp"
    app:np_dividerColor="#FF0000"
    app:np_textColor="#000000"
    app:np_textSize="16sp"
    app:np_min="0"
    app:np_max="100"
    app:np_value="50"/>

3. 在 Activity 中初始化 NumberPicker

在 Activity 中找到 NumberPicker 控件并设置监听器:

import com.shawnlin.numberpicker.NumberPicker;

public class MainActivity extends AppCompatActivity {

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

        NumberPicker numberPicker = findViewById(R.id.number_picker);
        numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                Log.d("NumberPicker", "oldVal: " + oldVal + ", newVal: " + newVal);
            }
        });
    }
}

应用案例和最佳实践

1. 时间选择器

NumberPicker 可以用于创建时间选择器,例如选择小时和分钟:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <com.shawnlin.numberpicker.NumberPicker
        android:id="@+id/hour_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:np_min="0"
        app:np_max="23"
        app:np_value="12"/>

    <com.shawnlin.numberpicker.NumberPicker
        android:id="@+id/minute_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:np_min="0"
        app:np_max="59"
        app:np_value="30"/>
</LinearLayout>

2. 自定义样式

通过设置不同的属性,可以自定义 NumberPicker 的样式:

<com.shawnlin.numberpicker.NumberPicker
    android:id="@+id/number_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:np_dividerColor="#00FF00"
    app:np_textColor="#FF0000"
    app:np_textSize="20sp"
    app:np_min="10"
    app:np_max="100"
    app:np_value="50"/>

典型生态项目

NumberPicker 可以与其他开源项目结合使用,例如:

1. MaterialDateTimePicker

MaterialDateTimePicker 是一个用于选择日期和时间的库,可以与 NumberPicker

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起