Skip to content
Advertisement

editText.getText().toString() can’t enter data

I am trying to make an app in which I can add subjects and my grades, currently, I am working on a system for adding subjects. So, I have a button, when pressed it makes an editText “field” in which you can enter the name for the subject. The problem is, when you enter some text and press ENTER, it makes a new line in the “field”. It doesn’t “process” the text I wrote, it just makes a new line.

Does anyone know a fix for this? Thanks!

Picture of the issue: https://i.stack.imgur.com/HiXjM.png

Here is the code that runs when you press the button:

        EditText editSubjectName = new EditText(this);
        editSubjectName.setHint("Enter subject name");
        linearLayout.addView(editSubjectName);
        String name = editSubjectName.getText().toString();

        TextView subjectName = new TextView(this);
        subjectName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        subjectName.setText(name);
        linearLayout.addView(subjectName);

Advertisement

Answer

Kindly use below sample

EditText editSubjectName = new EditText(this);
editSubjectName.setHint("Enter subject name");
editSubjectName.setSingleLine(true);
linearLayout.addView(editSubjectName);


TextView subjectName = new TextView(this);
subjectName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.addView(subjectName);


editSubjectName.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
           String name = editSubjectName.getText().toString();
           subjectName.setText(name);
          return true;
        }
        return false;
    }
});
Advertisement