【问题标题】:Adding/removing edit text and a remove (X) on click单击时添加/删除编辑文本和删除 (X)
【发布时间】:2017-09-12 08:00:22
【问题描述】:

我是安卓开发新手。

我想在他们单击按钮(称为“联系人”)时添加 EditText 和删除按钮 ( X )。这样会有多个联系人。单击删除按钮后,相应添加的带有删除按钮的 EditText 应该会消失。

会是这样的,

————————— X

————————— X

————————— X

————————— X

 ———————
|contact|  
 ———————

如果我使用任何适配器,如何添加空的 EditText 和删除按钮 ( X )。如果没有其他更好的选择? 最后,我需要获取 EditText 中输入的所有值。

注意:单击“联系人”时,应添加 EditText 和删除按钮 ( X )。

请给我一个清晰而简单的方法来做到这一点。

谢谢!

【问题讨论】:

标签: android android-edittext


【解决方案1】:

创建一个LinearLayout 和按钮。在按钮上单击调用以下方法。此外,在您的 onCreate 方法中创建一个 List<EditText> 以跟踪所有添加的编辑文本并稍后检索文本。

private void createNewEditText() {
    EditText editText = new EditText(this);
    editText.setMaxLines(1);
    editText.setSingleLine(true);
    editText.setLayoutParams(ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    editText.setCompoundDrawablesWithIntrinsicBounds(null, null, VectorDrawableCompat.create(resources, R.drawable.ic_clear_black_24dp, null), null);
    editText.setOnTouchListener(new View.OnTouchListener {
        @Override 
        Boolean onTouch(View view,MotionEvent event) {
            val DRAWABLE_BOTTOM = 3
            val DRAWABLE_RIGHT = 2
            val DRAWABLE_LEFT = 0
            val DRAWABLE_TOP = 1
            if (event.getRawX() >= (editText.right - editText.getCompoundDrawables()[DRAWABLE_RIGHT].bounds.width())) {
                editTextList.remove(editText);
                parentLinearLayout.removeView(editText);
                return true;
            }
            return false;
        }


    })
    editText.requestFocus();
    editText.setText(voicetext);
    editTextList.add(editText);
    parentLinearLayout.addView(editText);
}

【讨论】:

    【解决方案2】:

    您可以使用 LinearLayout 并将 orientation 设置为垂直。然后,您可以使用您的EditTextButton 创建另一个布局,并将它们动态添加到onClick 方法中的LinearLayout 联系按钮。

    不要忘记为新添加的视图生成不同的 ID,以便以后能够找到它们

    然后 X 按钮将从布局中删除其父级

    【讨论】:

    • 好..不要忘记接受答案,这样其他人也可以受益
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 2016-12-27
    • 2018-04-02
    • 2016-10-13
    相关资源
    最近更新 更多