Issue
i've this code :
nameInputLayout.requestFocus();
argentInputLayout.getEditText().setOnEditorActionListener((v, actionId, event) -> {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_DONE) {
addNewFields(this,layoutNewDepenses);
handled = true;
View lastChargeView = layoutNewDepenses.getChildAt(layoutNewDepenses.getChildCount() - 1);
TextInputLayout nameInputLayout = lastChargeView.findViewById(R.id.nom);
nameInputLayout.requestFocus();
TextInputLayout argentInputLayout = lastChargeView.findViewById(R.id.argent);
argentInputLayout.getEditText().setOnEditorActionListener((v2, actionId2, event2) -> {
boolean handled2 = false;
if (actionId2 == EditorInfo.IME_ACTION_DONE) {
addNewFields(this,layoutNewDepenses);
handled2 = true;
View lastChargeView2 = layoutNewDepenses.getChildAt(layoutNewDepenses.getChildCount() - 1);
TextInputLayout nameInputLayout2 = lastChargeView2.findViewById(R.id.nom);
nameInputLayout2.requestFocus();
TextInputLayout argentInputLayout2 = lastChargeView2.findViewById(R.id.argent);
argentInputLayout2.getEditText().setOnEditorActionListener((v3, actionId3, event3) -> {
boolean handled3 = false;
if (actionId3 == EditorInfo.IME_ACTION_DONE) {
addNewFields(this,layoutNewDepenses);
handled3 = true;
}
return handled3;
});
}
return handled2;
});
}
return handled;
});
It works perfectly but it's very repetitive. What i want to do is that whenever the user finishes writing in argentInputLayout Field and he clicks on the carriage return button, two more TextInputLayout Fields must be added.
The problem is that i don't know what number of fields could want the user and i don't want to do in the way i did it now because it will be too many lines of code. So can anybody help find how can i make it more simple ?
Solution
Avoid nesting anonymous objects, things can escalate quickly (as you can see). What I'd recommend you do is make your Activity/Fragment or whatever is containing this logic implement the OnEditorActionListener interface.
In the onEditorAction method check the id of the view. Do something like
if (actionId == EditorInfo.IME_ACTION_DONE) {
switch (v.id) {
case R.id.*id_of_your_first_edit_text* :
//do what you need to do for your first edit text - preferably extract in a separate method
break;
case R.id.*id_of_your_second_edit_text* :
//do what you need to do for your second edit text - preferably extract in a separate method
break;
....
}
And then for the set the OnEditorActionListener of your views to the Activity/Fragment that implements this interface. Now you will have a better structured code that is easier to understand.
I hope this gives you an idea on how to proceed.
Answered By - deluxe1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.