Dynamically add a Edit text

梦想的初衷 提交于 2019-12-14 00:02:39

问题


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?


回答1:


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.




回答2:


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.




回答3:


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);
    }


来源:https://stackoverflow.com/questions/8519040/dynamically-add-a-edit-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!