此代码是重复的并且工作完美。有人可以帮我让它更简单吗?

This code is repetitive and works perfect. Can somebody help me make it more simple?

我有这个代码:

    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;
    });

它运行完美,但重复性很高。我想要做的是,每当用户在 argentInputLayout 字段中完成写入并单击回车 return 按钮时,必须再添加两个 TextInputLayout 字段。

问题是我不知道用户需要多少字段,我不想像现在那样做,因为代码行太多。那么任何人都可以帮助找到我如何让它更简单吗?

避免嵌套匿名对象,事情会迅速升级(如您所见)。我建议你做的是让你的 Activity/Fragment 或任何包含此逻辑的东西实现 OnEditorActionListener 接口。

在 onEditorAction 方法中检查视图的 ID。做一些像

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;
         ....
    } 
         

然后将视图的 OnEditorActionListener 设置为实现此接口的 Activity/Fragment。现在您将拥有结构更好、更易于理解的代码。

我希望这能让您了解如何继续。