单击并填充另一个时如何添加另一个 EditText ( Android )

How add another EditText when I click and fill another ( Android )

我在谷歌上搜索了一段时间,但我找不到如何在单击一个 EditText 后添加另一个 EditText 的方法。

我试着用这张图来描述我的问题:

是否有提供此功能的容器?

您可以将所有 5 个添加到您的 XML 并将 android:visibility="gone" 分配给除第一个以外的所有。然后,您需要为它们中的每一个分配一个 TextWatcher,但为了简单起见,我将只显示一个。

et1.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                et2.setVisibility(TextUtils.isEmpty(s.toString()) ? View.GONE : View.VISIBLE);
                // The rest of them also???
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

如果您不想要固定数量的它们,您需要以编程方式创建 EditText,然后通过调用 addView 将它们添加到 ViewGroup 之一(RelativeLayout、LinearLayout、FrameLayout 等)方法

检查这个:

public class YourActivity extends Activity {
    private LinearLayout holder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activity);
        //get a reference to the LinearLayout - the holder of our views
        holder = (LinearLayout) findViewById(R.id.holder);
        addNewEdit();
    }

    private void addNewEdit() {
        //inflate a new EditText from the layout
        final EditText newEdit = (EditText) getLayoutInflater().inflate(R.layout.new_edit, holder, false);
        //add it to the holder
        holder.addView(newEdit);
        //set the text change lisnter
        newEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //here we decide if we have to add a new EditText view or to
                //remove the current
                if (s.length() == 0 && holder.getChildCount() > 1) {
                    holder.removeView(newEdit);
                } else if (s.length() > 0 && ((before + start) == 0)) {
                    addNewEdit();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}

your_activity.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/holder"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
</LinearLayout>

new_edit.xml:

<EditText xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

</EditText>

编辑:当然,您必须正确设置 paddings/margins,并可能为支架和您充气的物品创建您自己的样式布局。