Jump to content

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

Flanelman

Hey guys so 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: (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 with that within the inner class:

public class KeyListener implements View.OnKeyListener
    {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent)
        {
            //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 :)

Link to comment
Share on other sites

Link to post
Share on other sites

How do you think the KeyListener knows your String which is defined after KeyListener has been initialized?

 

Here's a suggestion:

 

public class KeyListener /* ... */ {
    private String username;
    
    public KeyListener(String username) {
        this.username = username;
    }
    
    // Your KeyUp thingy can process this.username now.
}
 KeyListener KL_Instance = new KeyListener(username);

Easy enough.

Write in C.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×