1

I'm very new to Java and OOP. Here is what I've got:

public class AmountChanged implements View.OnFocusChangeListener {

    @Override
    public void notFocused(View edittext1, boolean focused) {

//Do this awesome stuff

}

How do I instantiate and use this on one of my editText boxes in the mainActivity? I have already declared the editText boxes in the onCreate method.

REAL O G
  • 693
  • 7
  • 23

4 Answers4

1

Let's imagine you created an EditBox:

EditText editText = new EditText(this);

To set focus change listener, you should provide OnFocusChangeListener instance to the setOnFocusChangeListener. Since AmountChanged implements OnFocusChangeListener, you can do the following:

editText.setOnFocusChangeListener(new AmountChanged());

If you are going to use the same listener on many EditText items, you can save this listener as a variable somewhere:

View.OnFocusChangeListener myListener = new AmountChanged();
...
editText.setOnFocusChangeListener(myListener);
nikis
  • 11,166
  • 2
  • 35
  • 45
1

In your class where you are writing the code for the editext,in that activity's onCreate() method, you need to write

yourEditext.setOnFocusChangeListener(new AmountChanged());

Also give an eye to this please as you can use anonymous classes too.

Community
  • 1
  • 1
nobalG
  • 4,544
  • 3
  • 34
  • 72
0

In the onCreate method where you have the editText box(es) you want to use this with,

View.OnFocusChangeListener ac = new AmountChanged();
editText.setOnFocusChangeListener(ac);

From the View Android Developer Guide,

Set up listeners: Views allow clients to set listeners that will be notified when something interesting happens to the view. For example, all views will let you set a listener to be notified when the view gains or loses focus. You can register such a listener using setOnFocusChangeListener(View.OnFocusChangeListener). Other view subclasses offer more specialized listeners. For example, a Button exposes a listener to notify clients when the button is clicked.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Listener in android means that it is gonna listen to some event(OnTouchListener, OnClickListener, OnFocusChangedListener etc.). As you see OnFocusChangedListener interface is announced inside View class, in scope of Android it usually means that any child of View can produce this event, so you need to "listen" to those events.

In scope of EdiText what you have to do is something like this:

editText.setOnFocusChangedListener(new AmmountChanged());

EdiText is a child of View. So we are start "listening" to all OnFocusChanged events that will happen inside editText by registering our instance implementation OnFocusChangeListener.

Serge
  • 318
  • 3
  • 7