本文實例講述了Android實現EditText控件禁止輸入內容的方法。分享給大家供大家參考,具體如下:
問題:
android如何實現EditText控件禁止往里面輸入內容?
修改版解決方法:
EditText editText = (EditText) findViewById(R.id.editText1);editText.setKeyListener(null);
看到這個問題大家可能有點奇怪了,EditText的功能不就是往上面寫入內容嗎?
再者,如果真要禁止輸入文本,在布局文件中添加 android:focusable="false",
或者在代碼中使用editText.setFocusable(false),不就Ok了?
項目需求是這樣的,如果EditText上面已經被setText()內容,則需要禁止輸入,防止它被修改。
如果沒有顯示內容,則將EditText設置為可輸入狀態。
經過測試驗證:setFocusable方法的效果只有第一次使用時有效,也就是說若在布局文件里面設置:
android:focusable="false",即使你在代碼中設置此控件屬性:editText.setFocusable(true);也不能對它進行編輯。
即setFocusable方案不可行。經過摸索得出可行方案。
利用 editText.setInputType(InputType.TYPE_NULL);來禁止手機軟鍵盤。
editText.setInputType(InputType.TYPE_CLASS_TEXT);來開啟軟鍵盤。
應用程序默認為開啟狀態。
特別注意:這種方法也只能禁止軟鍵盤,若手機自帶硬鍵盤,此方案失效。
附測試demo:
public class EditTextTest extends Activity{  /** test EditText forbid input function demo */  EditText editText;  boolean flag = true;  public void onCreate(Bundle savedInstanceState)  {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    editText = (EditText) findViewById(R.id.editText1);    Button btn = (Button) findViewById(R.id.button1);    btn.setOnClickListener(new OnClickListener()    {      public void onClick(View v)      {        if (flag==true)        {          System.out.println("開啟軟鍵盤");           editText.setInputType(InputType.TYPE_CLASS_TEXT);          flag = false;        }else        {          System.out.println("禁止軟鍵盤");           editText.setInputType(InputType.TYPE_NULL);          flag = true;        }      }    });  }}希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答
圖片精選