Android的自定义数字Picker控件-NumberPicker使用方法

来源:互联网 发布:淘宝卖水果和干货吗 编辑:程序博客网 时间:2024/04/30 08:59

android-numberpicker是github的一个项目,提供了安卓中的自定义数字拾取控件,它的效果如图所示:



应用该控件也非常简单,使用如下几步即可:

1.从github上下载该控件,地址为:https://github.com/SimonVT/android-numberpicker;

2.将其中的library项目导入ADT;

3.在自己的project中引用该项目;

4.在要使用该控件的layout中找一个位置加入控件,格式如下:

<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:gravity="center">    <net.simonvt.numberpicker.NumberPicker        android:id="@+id/numberPicker"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:id="@+id/btn_getval"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="get value" /></LinearLayout>


5.通过如下代码操作此控件:

package net.simonvt.numberpicker.samples;import net.simonvt.numberpicker.NumberPicker;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;/** * @author Simon Vig Therkildsen <simonvt@gmail.com> */public class LightThemeActivity extends Activity {private LightThemeActivity c = this;private NumberPicker np;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_light);        np = (NumberPicker) findViewById(R.id.numberPicker);        String[] values = new String[]{"10","20","30","40","50","60","70","80","90","100","110","120","130","140","150","160","170","180","190","200","210","220","230","240","250"};        np.setMaxValue(values.length - 1);        np.setMinValue(0);        np.setDisplayedValues(values);        np.setFocusable(true);        np.setFocusableInTouchMode(true);        this.setNumberPickerValue(30);                Button btn_getvalue = (Button) this.findViewById(R.id.btn_getval);        btn_getvalue.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {Toast.makeText(c, "value = "+getNumberPickerValue(), Toast.LENGTH_SHORT).show();}});            }        public int getNumberPickerValue(){    if(np != null){    return (np.getValue()+1)*10;    }else{    return -1;    }    }        public void setNumberPickerValue(int val){    if(np != null){    np.setValue(val/10-1);    }    }}

其中:NumberPicker类的setMaxValue、setMinValue、setDisplayedValues、getValue和setValue方法需要自己体会使用。



0 0
原创粉丝点击