2014-09-26 179 views
1

我正在開發一個在線商店的應用程序。其中一個主要功能是搜索功能。由於我需要支持API 8及以上版本,而不是使用SearchView,我使用瞭如下的EditText來實現搜索視圖。如何處理輸入按鍵android

   <EditText android:id="@+id/search_edit" 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content" 
         android:layout_centerVertical="true" 
         android:layout_marginLeft="10dp" 
         android:layout_marginRight="10dp" 
         android:layout_toLeftOf="@+id/search_button" 
         android:background="@color/white" 
         android:ems="20" 
         android:imeOptions="actionDone" 
         android:maxLines="1" 
         android:textColor="@color/black" 
         android:textColorHint="@color/ebuy_color_second_strip" 
         android:textSize="18sp" > 
        </EditText> 

現在我想處理鍵盤的回車鍵,比用戶按下回車鍵時搜索活動開始。我所使用的代碼如下圖所示:

search = (EditText) findViewById(R.id.search_edit); 
     search.setOnKeyListener(new OnKeyListener() { 
      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       if ((event.getAction() == KeyEvent.ACTION_DOWN) 
         && (keyCode == KeyEvent.KEYCODE_ENTER)) { 

        String query_text = search.getText().toString().trim(); 

        try { 
         query_text = URLEncoder.encode(query_text, "utf-8"); 
        } catch (UnsupportedEncodingException e) { 

        } 
        String full_query = query_text; 

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(search.getWindowToken(), 0); 

         Intent bussiness = new Intent(EbuyHomeScreen.this, 
           EbuySearchActivity.class); 
         Bundle basket_buss_category = new Bundle(); 

         basket_buss_category.putString(EbuyUtils.TAG_CATEGORY_CODE, full_query); 

         bussiness.putExtras(basket_buss_category); 

         startActivity(bussiness); 

        return true; 
       } 
       return false; 
      } 

     }); 

這種方式適用於Android鍵盤和其他一些鍵盤非常好的,但是當我使用刷卡或迅速鍵盤等人性化的鍵盤是從谷歌下載Play商店不起作用,而不是以新行開始跳轉。有人能幫我解決這類問題嗎?

回答

0

嘗試setOnEditorActionListener在您的編輯文本。

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { 
@Override 
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
    if (actionId == EditorInfo.IME_ACTION_SEARCH) { 
     //your code here 
     return true; 
    } 
    return false; 
} 
}); 

您需要設置imeAction在你的EditText的xml文件:

<EditText 
    android:id="@+id/editTextUsername" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:ems="10" 
    android:hint="USERNAME" 
    android:inputType="text" 
    android:imeOptions="actionSearch" > 

    <requestFocus /> 
</EditText> 
+0

什麼關於XML的一部分,我應該改變那裏了? – Xhulio 2014-09-26 09:11:47

+0

@Xhulio你不需要更改你的xml – 2014-09-26 09:12:14

+0

@參數它不起作用,我也從IME_ACTION_SEARCH更改爲IME_ACTION_DONE,但它仍然不起作用。 – Xhulio 2014-09-26 09:41:52