I can not get a TextView to display the content present in an EditText!

0

I've created an app where your layout contains an EditText and a TextView .

The initial content of the TextView is: "unnamed" .

I'dliketheTextViewcontenttobechangedwhenIputsomethinginEditText,whichdoesnothappen:

I'veusedastringtocaptureEditTextcontentfortheTextViewdisplaythecontentsofit,sinceI'llalsoneedtoexporttoanextactivity.SoIdonotusesomethingdirectlike:

TextView.setText(editText),butTextView.setText(String).

MainActivity.java:

packagegenesysgeneration.ettotv;importandroid.support.v7.app.AppCompatActivity;importandroid.os.Bundle;importandroid.widget.EditText;importandroid.widget.TextView;publicclassMainActivityextendsAppCompatActivity{privateEditTextetNome;privateTextViewtvNome;privateStringnome;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etNome=(EditText)findViewById(R.id.etNome);tvNome=(TextView)findViewById(R.id.tvNome);if(etNome.getText().length()==0){nome="SEM NOME";
            tvNome.setText(nome);

        }else {

            nome=etNome.getText().toString();
            tvNome.setText(nome);

        }

    }
}
    
asked by anonymous 28.01.2017 / 21:53

1 answer

2

One way to do this is to use the addTextChangeListener() . Just below your conditions, add the code below:

etNome.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) {

              tvNome.setText(s.toString());
              nome = s.toString();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

Using the class TextWatcher , you basically have three methods:

  • onTextChanged : What you have inside it runs during text change.

  • afterTextChanged : What's inside it runs immediately after the text changes.

  • beforeTextChanged : What's inside it runs the moment before the text changes.

For more details, see in the documentation .

    
28.01.2017 / 22:14