Question

I have a EditText in my app. I want to override the @ key functionality such that as soon as the user hits the @ key while giving input in the EditText, the @ should be replaced by some string like "Hello world".

I have created something like below which shows a toast message when I hit the @ key. But I dont know how to implement it while working with a EditText.

Here is my code:-

@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();



        }
} 
Was it helpful?

Solution

InputFilter is the Proper way to do this kind of stuffs.

Proper Working Demo

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 });

    }

}

OTHER TIPS

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) 
    {
    }
);

in this code if on onTextChanged s==@ then replace it with Hello World

You just need to add

String replacedText = txtSample.getText().replace("@","Hello World");
txtSample.setText(replacedText);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top