Create EditText's dynamically
IAppConstants
IAppConstants
public interface IAppConstants {
float WEIGHT_0POINT3 = 0.3f;
float WEIGHT_0POINT7 = 0.7f;
float WEIGHT_SUM = 1.0f;
}
activity_main.xml
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="Orientation">
<!-- Fields will be created dynamically here -->
</ScrollView>
MainActivity
MainActivity
public class MainActivity extends AppCompatActivity {
private ScrollView mSVRootLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSVRootLayout = findViewById(R.id.rl_root);
LayoutParamsUtil.createEditTexts(this, new String[]{"Firsrt Name", "Last Name", "Eamil", "Country"},
new String[]{"Lokesh", "Kondaparthi", "Lokeshurl@gmail.com", "India"}, mSVRootLayout);
}
}
LayoutParamsUtil
LayoutParamsUtil
public class LayoutParamsUtil {
public static LinearLayout.LayoutParams getLLParamWeightWCWC(float weight) {
return new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, weight);
}
public static LinearLayout.LayoutParams getLLParamWeightMPWC(float weight) {
return new LinearLayout.LayoutParams(
0, ViewGroup.LayoutParams.WRAP_CONTENT, weight);
}
public static void createEditTexts(Context context,
String[] titleInHeading,
String[] hintInValueField,
ScrollView scrollLinearLayout) {
if(titleInHeading!= null && hintInValueField != null && titleInHeading.length == hintInValueField.length) {
LinearLayout llRootLayout = new LinearLayout(context);
llRootLayout.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < titleInHeading.length; i++) {
LinearLayout ll2ViewBinder = new LinearLayout(context);
ll2ViewBinder.setOrientation(LinearLayout.HORIZONTAL);
ll2ViewBinder.setWeightSum(WEIGHT_SUM);
TextView tvHeading = new TextView(context);
tvHeading.setText(titleInHeading[i]);
tvHeading.setTextSize(20);
tvHeading.setTextColor(context.getResources().getColor(android.R.color.black));
tvHeading.setLayoutParams(LayoutParamsUtil.getLLParamWeightWCWC(WEIGHT_0POINT3));
EditText etValueField = new EditText(context);
etValueField.setHint(hintInValueField[i]);
etValueField.setTextSize(20);
etValueField.setTag(titleInHeading[i]); //used to get Value from EditText
etValueField.setLayoutParams(LayoutParamsUtil.getLLParamWeightMPWC(WEIGHT_0POINT7));
ll2ViewBinder.addView(tvHeading);
ll2ViewBinder.addView(etValueField);
llRootLayout.addView(ll2ViewBinder);
}
scrollLinearLayout.addView(llRootLayout);
}
}
}