2

我有一個對話框片段,允許用戶指定一些文本和文本的位置。如何處理警報對話框中的無效輸入?

dialog fragment

我想限制進入文本不是字符的一些上限的用戶。 我可以限制最大字符輸入嗎?否則,在這段代碼中,我可以包含一個檢查以確保文本小於LIMIT? 下面是代碼:

public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the Builder class for convenient dialog construction 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    final CharSequence[] items = {"Above", "Below"}; 
    capPos = Position.ABOVE; 

    final EditText input = new EditText(getActivity()); 
    input.setInputType(EditorInfo.TYPE_CLASS_TEXT); 
    input.setHint("Add caption here"); 
    builder.setView(input); 

    builder.setTitle(R.string.dialog_caption) 
      .setPositiveButton(R.string.proceed, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
       text = input.getText().toString(); 
       mListener.onDialogPositiveClick(CaptionFragment.this); 
       } 
      }) 
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        mListener.onDialogNegativeClick(CaptionFragment.this); 
       } 
      }) 
      .setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id){ 
        if ("Above".compareTo(items[id].toString()) == 0){ 
         capPos = Caption.Position.ABOVE ; 
         Log.i("CaptionFragment", "Above"); 
        }else if ("Below".compareTo(items[id].toString()) == 0){ 
         capPos = Caption.Position.BELOW; 
         Log.i("CaptionFragment", "Below"); 
        } 
       } 
      }); 
    // Create the AlertDialog object and return it 
    return builder.create(); 
} 

回答

2

所以它是一個EditText。您可以使用attiribute android:maxLength來限制此處顯示的字符數https://stackoverflow.com/a/3285421/655987

另一種選擇是讓用戶輸入他/她想要的任何內容,然後執行檢查背景。

你可以在你的OnClickListener裏面這樣做。如果你想,只有當用戶點擊肯定按鈕哪位通常是個案來檢查值,那麼你應該這樣做如下:

... 
.setPositiveButton(R.string.proceed, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
      text = input.getText().toString(); 
      if(text.equals("ads")) //For example 
       ... 
      } 
     }) 
... 

此外,您還可以初步確定了積極的按鈕onClickListenernull然後覆蓋它,如此處所示https://stackoverflow.com/a/7636468/655987

這取決於您。

1

試試這個,

final EditText input = new EditText(getActivity()); 
    input.setInputType(EditorInfo.TYPE_CLASS_TEXT); 
input.setFilters(new InputFilter[] { 
      new InputFilter.LengthFilter(LIMIT) }); 
    input.setHint("Add caption here"); 
    builder.setView(input);