show an element based on what in a edittext in android

47 Views Asked by At

I am a newcomer in android. Please forgive me if i am asking anything stupid.

I want to show/hide an element (TextView) based on the user input in an EditText element.

Basically there are 3 textview . Based on what is being entered in the edittext, only one of them should be shown ( in this example if mometasone is entered in the edittext, the textview with id strongsteroidtext should be shown and others should hide)

Here is the code pattern that I am using.

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    EditText creamname = (EditText) findViewById(R.id.creamname);
    TextView nosteroid = (TextView) findViewById(R.id.nosteroidtext);
    TextView weaksteroid = (TextView) findViewById(R.id.weaksteroidtext);
    TextView strongsteroid = (TextView) findViewById(R.id.strongsteroidtext);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final String cream = (creamname.getText().toString().trim());
    weaksteroidlist = R.string.weaksteroidlist;
    {if (cream.equals("beclomethasone")) {

        weaksteroid.setVisibility(View.VISIBLE);
        nosteroid.setVisibility(View.INVISIBLE);

    }
    if (cream.equals("mometasone")) {
        strongsteroid.setVisibility(View.VISIBLE);
        nosteroid.setVisibility(View.INVISIBLE);

    } else weaksteroid.setVisibility(View.INVISIBLE);
    strongsteroid.setVisibility(View.INVISIBLE);
    nosteroid.setVisibility(View.VISIBLE);
}

Now, when I am running this, apparently the "else" statement is only working, which means the "nosteroid" text that is supposed to be visible by this is visible. But when mometasone is being entered, nothing happens ( means the if statement is not working).

What am I getting wrong? please guide me.

1

There are 1 best solutions below

0
On

OnCreate() method is called only the first time the view is created, not every time the text changes in ur EditText. Study android activity life circle first.

What you want can be achieved by registering ur editText with onKeyListener or onTextChangeListener

And aware this:

else
statement 1;
statement 2;

Is equal to

else {
statement 1;
}
statement 2;