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

时间:2019-11-11 10:11:41

标签: android onclicklistener buttonclick

我的活动中有一个EditText,每次用户按下键盘上的Enter键时,使用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);
    }

1 个答案:

答案 0 :(得分:1)

尝试使用:-

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:动作的标识符。这将是您提供的标识符,,如果由于按下回车键而被调用,则为EditorInfo#IME_NULL

     

事件:如果由Enter键触发,则为事件;否则为空。

onEditorAction

and setImeOptions(EditorInfo.IME_ACTION_NEXT)添加/设置软键盘以使其具有 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;
            }