Java – how do I add another EditText when I click and populate another (Android)

I googled for a while, but I couldn't find how to add another EditText after clicking on one

I try to describe my problem with this picture:

Are there any containers that provide this functionality?

resolvent:

Check:

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>

And new_ edit.xml:

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

</EditText>

Edit: of course, you must set the correct padding / margins and may create your own style layout for the holder and your inflated items

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>