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

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

Android的自定义数字Picker控件-NumberPicker使用方法_第1张图片


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

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

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

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

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




    

    


 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 
 */
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() {
			
			@Override
			public 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方法需要自己体会使用。



你可能感兴趣的:(编程技巧,Android技术)