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) {
			  
		  }
		});
	}



發佈了51 篇原創文章 · 獲贊 12 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章