2012-06-14 42 views
1

我需要一種在用戶按下「Enter」鍵後立即從「EditText」獲取文本的方法,如果失去焦點,它也應該調用方法。關於使用EditText的建議

我創建的EditText這樣的:

<EditText 
     android:id="@+id/editText1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_toRightOf="@+id/button2" 
     android:ems="10" > 
+0

[這裏](http://stackoverflow.com/questions/1489852/android-handle-enter-in-an-edittext)是它。 – Sajmon

回答

1

要獲得按鍵您的EditText需要有重點:

editText1.setFocusableInTouchMode(true); 
editText1.requestFocus(); 

然後設置onkeylistener ():

editText1.setonKeyListener(new OnKeyListener(

@override onKey(View v, int keyCode, KeyEvent event) { 
if(event.getAction()==KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){ 
// what you need to do when Enter is pressed 
return true; 

}else return false; 

} 

對於焦點丟失,您需要實施View.onFocusChange接口和檢查hasFocusfalse

+0

謝謝...當我按下「enter」鍵時,如何隱藏鍵盤? – Antilope

+0

檢查此類似的問題http://stackoverflow.com/questions/1109022/how-to-close-hide-the-android-soft-keyboard –

1

使用一個EditText動作偵聽器。請參考這個問題,它可能是相同的:Handle Enter in EditText

對於重點檢測損失:

if(!(et.isFocused)){ 
    //call your method here 
} 
+0

你好,我可以有一個方法來處理事件? – Antilope