动态添加视图后,按钮 onClick 不会触发

Button onClick doesn't trigger after adding views dynamically

我的 activity 中有一个 EditText,每次用户按下键盘上的输入按钮时,使用 OnEditorActionListener 另一个 EditText 将被添加到 LinearLayout。
问题是在添加这些视图后,Button onClick 不起作用。为什么会发生这种情况以及如何解决?

按钮onClick

btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(NewExpenseActivity.this, "Saved", Toast.LENGTH_SHORT).show();
            }

        });  

.

private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
            createNewEditText();
        }

        return false;
    }
};  

.

public void createNewEditText() {
        textInputLayout = new TextInputLayout(this);
        textInputLayout.setPadding(padding_in_px_16, padding_in_px_8, padding_in_px_16, padding_in_px_8);
        editText = new EditText(NewExpenseActivity.this);
        editText.setId(id);
        editText.setHint("Enter Name");
        editText.setInputType(InputType.TYPE_CLASS_TEXT);
        editText.setOnEditorActionListener(editorActionListener);
        editText.setImeOptions(EditorInfo.IME_ACTION_NEXT);
        textInputLayout.addView(editText);
        ITEM_MAP.put("Key" + idNum, id);
        idNum++;
        linearEtList.addView(textInputLayout);
    }

尝试使用:-

private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (event != null) {
            createNewEditText();
        }

        return false;
    }
}

因为:-

actionId int: Identifier of the action. This will be either the identifier you supplied, or EditorInfo#IME_NULL if being called due to the enter key being pressed.

event If triggered by an enter key, this is the event; otherwise, this is null.

onEditorAction

和 setImeOptions(EditorInfo.IME_ACTION_NEXT) adds/sets 软键盘有一个 NEXT (--->|) 按钮。仅当使用该软按钮时,actionId == IME_ACTION_NEXT.

喜欢

enter image description here

如果你两者都想要,那么你可以做

            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT || (event != null &&  event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    addEditText();
                }
                return false;
            }