Dynamically add a Edit text

2019-10-03 04:30发布

I want to add an edit text field to my app when i click a button, but i do not change the layout. Just add it below an existing one defined by the xml file. Lets say i have a contacts app and if the user needs to add an extra field hit the button and creates one! How to do that?

3条回答
别忘想泡老子
2楼-- · 2019-10-03 04:51

What you can do is have those EditText's in a panel, i.e. group them in panels, then have a button, and on button click create an instance of an EditText and add it to the relevant panel. This way you are not limiting yourself to being only able to add one panel, but as much as the user would like to add.

查看更多
Fickle 薄情
3楼-- · 2019-10-03 04:58

First of all you call the data from the webservice.

For example: description = Parser.getDescription;

In the xml layout:

 <Button android:id="@+id/button" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:onClick="@string/ButtonClick"/>

 <EditText android:id="@+id/note" android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

Code:

        ButtonName  = (Button)findViewById(R.id.note);
        Data    = (EditText)findViewById(R.id.note);
        public void ButtonClick(View v){            
        description = Parser.getDescription;
        Data.settext(description);
    }
查看更多
霸刀☆藐视天下
4楼-- · 2019-10-03 05:09

Keep an EditText item in your layout and set its visibility to gone.

 <EditText android:visibility="gone" android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

Then on the onClick event of the button set visibility to visible.

or

You can add the EditText items programmatically.

Add a LinearLayout to your xml.

<LinearLayout
        android:id="@+id/editTextGroupLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

On button click event add EditText programmatically.

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.editTextGroupLayout);
    EditText editTextView = new EditText(this);
    editTextView.setGravity(Gravity.CENTER);

    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1);

    editTextView.setLayoutParams(params);

    linearLayout.addView(editTextView);

Hope this would help.

查看更多
登录 后发表回答