简体   繁体   中英

Android - How to display keyboard input in TextView as it is typed

In part of my android application I am trying to show the text I am typing as it is being typed WITHOUT a button/button listener. In other words I want to see the text in an EditText sent in real time to a TextView. Is this possible?

//To open keyboard forcefully, mention the code into any listener or oncreate

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

//To Trace Pressed Key

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
        case KeyEvent.KEYCODE_A:
        {
            textview.setText("A");
            //your Action code
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

You can accomplish this by calling addTextChangedListener on the EditText, and creating a new TextWatcher.

EditText editText = findViewById(R.id.edit_text);
editText..addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
          changeTextView();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

You can use an EditText TextChangedListener.

textView = (TextView)findViewById(R.id.text_view);
editText = (EditText)findViewById(R.id.edit_text);
editText.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        textView.setText(editText.getText().toString());
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM