2016-07-24 110 views
1

我目前正在嘗試使用AlertDialogs。如何「取消」按鈕按?

目前,我在我的AlertDialog中有一個EditText,並且希望將輸入限制爲只有整數。我使用了一個基本的try和catch塊來避免應用程序崩潰,形成NumberFormatException。

但是,我想設置它,以便當用戶嘗試按不正確的輸入按鈕時,輸入不會註冊並且不會取消對話框。

UpperLimitDialog.setPositiveButton(R.string.Positive_Button, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int i) { 
         int RawInput = settings.getInt("UpperLimit", 12); 
         try { 
          RawInput = Integer.parseInt(input.getText().toString()); 
         }catch (NumberFormatException se) { 
          Toast.makeText(SettingsMenu.this, "Non-Integer Value, No Input", Toast.LENGTH_SHORT).show(); 
         //Here I want the app to not register the click and prevent the dialog box from closing. 
         } 
         editor.putInt("UpperLimit", RawInput); 
         editor.apply(); 
         Toast.makeText(SettingsMenu.this, "Set Upper Limit to " + RawInput, Toast.LENGTH_SHORT).show(); 
        } 
       }); 

我可以用什麼方法來達到這個目的?

+0

爲什麼不使用使用XML輸入型的號碼,這樣你不需要檢查工作,任何情況下,一個字符串值 –

+0

我以爲我可以不使用自定義XML而只是刮掉它。但我想不是,最好切換回使用XML。 –

+0

它取決於你。如果你想你可以嘗試Linos答案並保持警告對話框,直到它的數字輸入 –

回答

0

在EditText上的XML代碼只需使用:

android:inputType="numberSigned" 

這將讓用戶僅輸入整數。希望這可以幫助!

2

使用可以通過兩種Java或XML acheive input to only Integers這一點。

的Java

editText.setInputType(InputType.TYPE_CLASS_NUMBER); 

XML

android:inputType = "numberSigned" 

這或許可以幫助你在這兩種方式。

1

如果限制用戶只允許數量,那麼你可以簡單地嘗試與 -

安卓的inputType =「號」

,如果你想允許浮動號碼,然後嘗試用 -

安卓的inputType = 「numberDecimal」

和如果要禁用對話框按鈕,然後嘗試這個 -

Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); 
theButton.setEnabled(false); 

會爲你:)