flanelman
flanelman

Reputation: 39

Android studio - how to access EditText from within inner class?

Hey guys pretty new to android studio, like the title says I've tried to put the text within the EditText into a var called "username" which I want to be able to use within my inner class but I don't know how to make it accessible from within.

here's what I do with the EditText, within the onCreate: (KeyListener is the name of my inner class)

KeyListener KL_Instance = new KeyListener();
EditText input_text = (EditText) findViewById(R.id.inputText);
input_text.setOnKeyListener(KL_Instance);

String username = input_text.getText().toString();

And here's what i'm trying to do within the inner class:

public class KeyListener implements View.OnKeyListener
{
    @Override
    public boolean onKey(View view, int keyCode, KeyEvent keyEvent)
    {
        if (keyCode == KeyEvent.KEYCODE_AT)
        {
            Toast.makeText(MainActivity.this, "Do not type @", Toast.LENGTH_LONG).show();
        }

        //if the enter key is pressed, then check to see if username is 8 or more chars
        if (keyCode == keyEvent.KEYCODE_ENTER)
        {
            //if it is, display it
            if(username.length => 8)
            {
                Toast.makeText(MainActivity.this, "Hi, " + username, Toast.LENGTH_LONG).show();
            }else //else, ask for a username of atleast 8 chars
            {
                Toast.makeText(MainActivity.this, "Please enter a username that is 8 or more chars", Toast.LENGTH_LONG).show();
            }
        }

        return false;
    }
}

But it says "cannot resolve symbol 'username'" and I cant access "input_text" within that class either so If someone could help me out here it would be greatly appreciated, Thanks in advance :)

Upvotes: 0

Views: 179

Answers (1)

Timo
Timo

Reputation: 513

If you want store the value of the EditText you will need to update it with your listener and why use a KeyListener and why not just a TextWatcher like in this post here

EDIT :

You should do something like that

input_text.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged (Editable s){
        username = s.toString();
    }

    @Override
    public void beforeTextChanged (CharSequence s,int start,
    int count, int after){
    }

    @Override
    public void onTextChanged (CharSequence s,int start,
    int before, int count){
    }
});

TextWatcher is an implementation of the Design Pattern Observer so this code will be triger each time someone use the EditText, you have to deal with this by doing your logic in the TextWatcher like calling service or something else in charge of handle the username.

Upvotes: 1

Related Questions