Search code examples
androidandroid-edittext

Generating Edit Text Programmatically in Android


I'm developing Contact Application, which adds Email address, phone number. I have to create edit text dynamically in code itself. I don't know how and where to implement this logic, suggest any help would be grateful.


Solution

  • You can create it like so:

    EditText myEditText = new EditText(context); // Pass it an Activity or Context
    myEditText.setLayoutParams(new LayoutParams(..., ...)); // Pass two args; must be LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, or an integer pixel value.
    myLayout.addView(myEditText);
    

    This can be implemented anywhere on the UI thread; a click listener, an onCreate method, and everything in between.

    There is a more generic example in this question, and a good rundown of these processes in this blog.