2016-11-07 66 views
2

我有這個AlertDialog顯示當用戶按下浮動按鈕。我不希望用戶能夠插入多行輸入(即如果她試圖按下回車鍵,則忽略她)。我該怎麼做呢?這裏是我的代碼:如何在警報對話框中強制輸入單行?

final EditText input = new EditText(getActivity()); 
    new AlertDialog.Builder(getActivity()).setTitle("Package creation").setMessage("Insert package name:").setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialogInterface, int i) { 
         CharSequence toastText; 
         if (input.length() > 0) { 
         /* save the package name in the database */ 
          toastText = getString(R.string.toast_package_saved); 
         } else toastText = getString(R.string.toast_empty_text); 
         Toast toast = Toast.makeText(getActivity(), toastText, Toast.LENGTH_SHORT); 
         toast.show(); 
         input.getText().clear(); 
        } 
       }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialogInterface, int i) { 
         // do nothing 
        } 
       }).show(); 
+0

輸入視圖是一個EditText? – androidevil

+0

是的。對不起:我忘了在代碼中添加該行!我會立即修復它。 – Robb1

回答

2

以XML

android:maxLines="1"在EditText上輸入XML佈局。

同樣選擇InputType,正如FrédéricLetellier在他的回答中提到的那樣。

例如,在Specifying the Input Method Type

android:inputType="phone"

更多信息在Java

input.setMaxLines(1); 
input.setInputType(InputType.TYPE_CLASS_PHONE); 

在這些例子中,它表現出對電話號碼的設置。您可以在InputType


PS查看其他類型:另外在XML,可以使用android:singleLine="true",但這個參數已被棄用。所以第一個選項聽起來更好。

+0

謝謝! Java完全按照我的意圖工作。 **注意**在我的具體情況下,我需要'TYPE_CLASS_TEXT'。 – Robb1

0

使用以下屬性的EditText上即輸入查看

 android:ellipsize="end" 
1

定義的最大行單獨在不改變的inputType不夠

在XML,使它看起來像單行的EditText:

android:maxLines="1" 

此外,要防止進入一個新的行:

android:inputType="text" 

哪個translat es以編程方式:

input.setMaxLines(1); 
input.setInputType(InputType.TYPE_CLASS_TEXT); 
+0

這適用於xml的情況......但是當我使用** alert對話框時**我需要一些能夠從java文件中完成的東西(我想,除非我失去了一些東西)。 – Robb1

+0

@ Robb1看到我編輯的問題。 – androidevil