Search code examples
androidandroid-edittexttextviewadvanced-custom-fieldsprogrammatically-created

Create Custom Fields Programmatically combining Textview and EditText


I'm working on making dynamic form from the Strings received from JSON Response of the API.

Here I want to create a dynamic form where I want to identify {field_name} and replace it into EditText.

String given below is a string received from the API Response and yes it contains "{}" as a part of string.

So I am finding for them with the help of while loop and creating EditText for each time that a {} is found.

Now the problem that I am not able to resolve is how to append those EditText with the String/TextView.

For Example,

String demo = "{event_name} Event on{event_date} at {event_time} venue {event_venue} All are welcome. -";

Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(str);

EditText et;

while (m.find()) {
   LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, 
   LinearLayout.LayoutParams.WRAP_CONTENT);
   lp.setMargins(10, 10, 10, 10);
   et = new EditText(this);
   Log.e("onCreateInternal: ", "=" + i);

   SmsTypeGroup.addView(et, lp)
}

After Replacing the {} with EditText from the String the desired output is as below.

Required output is as shown in this Image

Any Help would be great.

Thanks in advance.

Note: The Only condition is that the whole process is to be done programmatically from Java file, no use of XML.


Solution

  • i gather english is not your first language, but if i understand correctly, what you are getting right now is just a view with 4 editText, and you need a way to additionally add textviews with the text inbetween the {} elements in the string.

    one way to do this would be to use split instead of the patternmatch:

    String demo = "{event_name} Event on{event_date} at {event_time} venue {event_venue} All are welcome. -";
    String[] parts = demo.split("}");
    
    EditText et;
    
    for(String part : parts){
       LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT);
       lp.setMargins(10, 10, 10, 10);
       et = new EditText(this);
    
       SmsTypeGroup.addView(et, lp);
    
       String[] _parts = part.split("{");
       if(_parts.length >1){
         TextView tv = new TextView(this);
         tv.text = _parts.[0];
         SmsTypeGroup.addView(tv, lp)
       }
    }