简体   繁体   中英

How do I get user input into an EditText field

I am building a larger app and I made this small one just to figure out how to accomplish getting text from user input however it is not working. If I create a string reference at the Text property of my EditText field it works ok. If I leave it blank and enter the text into the field when the application runs in my emulator it does not work. Any ideas.

package com.example.stringtest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import android.view.View;

import android.widget.EditText;
import android.widget.Button;

public class Main extends Activity {

EditText display;
EditText displayTwo;
String displayContents;
Button displayText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainlayout);

    display = (EditText) findViewById(R.id.editText1);
    displayContents = display.getText().toString();

    displayTwo = (EditText) findViewById(R.id.editText2);


    displayText = (Button) findViewById(R.id.button1);

    displayText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            displayTwo.setText(displayContents);

        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainlayout, menu);
    return true;
}
}

displayContents = display.getText().toString();

The displayContents will not be updated when the text inside the EditText changes.

Instead of doing this you should call getText() every time you want to get the current text value.

If you want to be notified every time the text in the EditText is being changed then you should add a listener to the appropiate event. In this case it's EditText.addTextChangedListener .

More information about that: http://developer.android.com/reference/android/widget/TextView.html#addTextChangedListener(android.text.TextWatcher )

Try this instead!

   displayText.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
      displayContents = display.getText().toString();
            displayTwo.setText(displayContents);

        }
    });

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