1. 程式人生 > >Android EditText 輸入數字和小數,設定輸入的範圍0.001-1000

Android EditText 輸入數字和小數,設定輸入的範圍0.001-1000

要求實現的效果:EditText的輸入資料值的範圍是0.001-1000

因為EditText輸入的是數字和小數,兩種型別。

佈局型別:

    <EditText
        android:id="@+id/et_num"
        android:layout_width="fill_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:numeric="decimal" />
程式碼的實現:
	/**
	 * 輸入框輸入值的範圍  1000-0.001(EditText的屬性:android:numeric="decimal")
	 * @param txtInput
	 */
	public static void setRegion(EditText txtInput)
	{
		txtInput.addTextChangedListener(new TextWatcher() 
		{
		  public void afterTextChanged(Editable edt) 
		  {
		    String temp = edt.toString();
		    int posDot = temp.indexOf(".");
		    //小數點之前保留3位數字或者一千
		    if (posDot <= 0){
		    	//temp
		    	if(temp.equals("1000")){
		    		return;
		    	}else{
				    if(temp.length()<=3){
				    	return;
				    }else{
				    	edt.delete(3, 4);
				    	return;
				    }
			    }
		    }
		    //保留三位小數
		    if (temp.length() - posDot - 1 > 3)
		    {
		    	edt.delete(posDot + 4, posDot + 5);
		    }
		  }
		  public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			  
		  }
		  public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			  
		  }
		});
	}