Self taught PHP, now learning java and javascript.
In java/android is it good practice to add the same event listener to different components and how does one tell which component is in use?
//set up view components
listTitleET = (EditText) findViewById(R.id.listTitleEditText);
finishDateET = (EditText) findViewById(R.id.finishDateEditText);
startDateET.setOnFocusChangeListener(v);
finishDateET.setOnFocusChangeListener(v);
View.OnFocusChangeListener v = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
/*************
* Do something here
* But how does one know which event is in use ..?
}
};
Thanks in advance
I always prefer to have a separate event listener for each component, or to create a class that extends the event listener and have a separate instance for each. I think it is cleaner and eaiser to maintain as it avoids long switch
or if...else if
statements. So, You can do a few different things: Create two different instances of View.OnFocusChangedListener
say v1
and v2
and use
startDateET.setOnFocusChangeListener(v1);
finishDateET.setOnFocusChangeListener(v2);
Where the overridden methods have the appropriate code corresponding to each view.
Or you can set an id or tag on each of your EditText
views and then have some logic like
if(v.getId.equals(...))
...
else if (v.getId().equals(...))
...
inside the overridden method. As you can see, if you choose to edit your code later you may have to untangle a long such if/switch statement.
The argument "v" in the onFocusChange
method tells you which View
triggers the event.
From there you can even access the listener from the listener itself, through:
v.getOnFocusChangeListener();
Note that I advise you to change the listener's name to something other than "v", it's quite confusing otherwise.
Edit
Note: if you require to access references to any component, etc. outside the anonymous class (your listener), you must declare the component (or anything) final
.
You can use the same listener for example with onClick, you use something like this:
View.OnClickListener myListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button:
{
//do something
break;
}
case R.id.button2 :
{
//do something
break;
}
}
}
You only need to know which view throw the event.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.