java – 当我点击并填充另一个(Android)时,如何添加另一个EditText

我谷歌搜索了一段时间,但我找不到如何添加另一个EditText后点击其中一个.

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

是否有一些容器提供此功能?

最佳答案
检查一下:

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>

编辑:当然,你必须设置正确的填充/边距,并可能为持有人和你膨胀的项目创建自己的风格布局.

转载注明原文:java – 当我点击并填充另一个(Android)时,如何添加另一个EditText - 代码日志