简体   繁体   中英

How do I print text from EditText to a textview when pressed enter or a button

So I want the text the person wrote in the EditText box to be printed on the screen when pressed enter or clicked on the button.

    final TextView txt= findViewById(R.id.empty_text);
    Button   btn =      findViewById(R.id.button_add);
    final EditText tst = findViewById(R.id.test_textEdit);


    final String value = tst.getText().toString();


    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            txt.append(value+"\n");
            tst.setText("");
        }
    });

I think txt.append(value+"\\n"); I think I need something that tells the computer to print the text but I don't find one.

value is only set once, and before you assign your ClickListener . Just pull whatever text is present inside your EditText every time onClick() is called.

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        txt.setText(tst.getText().toString());
    }
});

Edit: I just realised you were looking to update the TextView on an "Enter" key press as well. For that you can try:

tst.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int id, KeyEvent event) {
        if (id == EditorInfo.IME_NULL) {
            txt.setText(tst.getText().toString());
            return true;
        }
        return false;
   }
});

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