简体   繁体   中英

Return user input from Android EditText field

I am new to Android dev. and to Programming in general. I have a text based RPG I wrote in Java as a terminal app, and I am trying to recreate it as an Android app; however, I am getting stuck quite at the beginning.

How can I return the user input from an EditText view and store that value in a String?

Below is a throwaway project I made to figure out the problem:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String a = "Hello from";
    String b = "the other";
    String c = "SIDE!";
    String d = "What you don't like Adele?";

    final String userIn;

    final EditText editText = (EditText) findViewById(R.id.editText);
    TextView textView = (TextView) findViewById(R.id.viewText);

    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                handled = true;
            }
            return handled;
        }

        private void sendMessage() {
            userIn = editText.getText().toString();
        }
    });

}

I cannot change the value of userIn because it has to be final to work in the function. I'm sure I'm missing something obvious, but any help would be grand!

Declare userin outside of onCreate() and will work to change it . Check this :

public class MainActivity extends AppCompatActivity {
String userIn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String a = "Hello from";
    String b = "the other";
    String c = "SIDE!";
    String d = "What you don't like Adele?";



    final EditText editText = (EditText) findViewById(R.id.editText);
    TextView textView = (TextView) findViewById(R.id.viewText);

    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessage();
                handled = true;
            }
            return handled;
        }

        private void sendMessage() {
            userIn = editText.getText().toString();
        }
    });

}

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