2014-02-11 89 views
1

我在我的應用程序中有EditText。我想覆蓋@的關鍵功能,例如,只要用戶在輸入EditText的同時點擊@鍵,就應該用「Hello world」之類的字符串替換@。當某個鍵被按下時,將EditText輸入更改爲字符串android

我創建了類似下面的內容,當我點擊@鍵時顯示吐司消息。但我不知道如何在使用EditText的同時實現它。

這裏是我的代碼: -

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    { 
     // TODO Auto-generated method stub 
     if(editText1.isFocused() && event.isShiftPressed() && keyCode == KeyEvent.KEYCODE_2) 
     { 
      //txtSample.setText("Hello"); 
      Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show(); 



     } 
} 

回答

0

InputFilter是做這種東西的正確方法。

正確的工作演示

public class MainActivity extends Activity { 

    private EditText editText; 
    private InputFilter filter = new InputFilter() { 

     @Override 
     public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { 

      if (source != null && ("" + source).equals("@")) { 
       return "Hello World"; 
      } 
      return null; 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     editText = (EditText) findViewById(R.id.editText); 
     editText.setFilters(new InputFilter[] { filter }); 

    } 

} 
+0

很好用!謝謝。順便說一句,如果我們可以在WebView中實現EditText字段? – user2625086

0
mMyEditText.addTextChangedListener(new TextWatcher() 
{ 
    public void afterTextChanged(Editable s) 
    { 
    } 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) 
    { 
     /*This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. It is an error to attempt to make changes to s from this callback.*/ 
    } 
    public void onTextChanged(CharSequence s, int start, int before, int count) 
    { 
    } 
); 

在此代碼,如果在onTextChanged小號== @然後用的Hello World替換

+0

感謝您的答覆。問題是如果我在「EditText」中輸入'abc @',一旦我點擊@鍵,文本就會在輸入後被添加,比如'abc @ xyz.com' – user2625086

0

你只需要添加

String replacedText = txtSample.getText().replace("@","Hello World"); 
txtSample.setText(replacedText); 
+0

感謝您的回覆。但我想你誤解了這個問題。只要用戶按下某個鍵,我想將EditText中的文本更改爲其他內容 – user2625086

+0

我只需編寫要用您的Toast語句替換的代碼即可。 –

相關問題