简体   繁体   中英

I want to add Edit Text dynamically not more not less than 5 Edit Texts in android java

I need to add 5 Input fields (EditText) dynamically one by one on button click and want to take values from them and store them into database using Room Persistence with MVVM.

Here I'm adding the view dynamically

private void addEditTextView() {
    View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
    EditText val1 = inputView.findViewById(R.id.input_value_1);
    binding.layoutList.addView(inputView);
}

Any suggestion would be very helpful. Thank you in advance.

"When I clicked Add button it is adding input field one by one, this code is working but I just want to limit for 5 fields not more not less and take values from them."

If you want to add exactly 5 fields on button click I recommend designing a fragment with the 5 fields in place, then when the button is clicked, inflate the fragment into your parent view. Then code the fragment appropriately with the data you're working with.

Then if you wanted, you could deflate the fragment on button click to clear the view or add some other way to clear the fragment when you want. Much easier than what you're doing currently in my own opinion.

You might as well include a submit button in your fragment assuming this is some kind of form.

You can simply define an integer and increase it every time you add the EditText but you should check if your integer is less than 5 everytime the method is called.

Example

private void addEditTextView() {
int count = 0;
if (count < 5){
View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
EditText val1 = inputView.findViewById(R.id.input_value_1);
binding.layoutList.addView(inputView);
count++;
}
}

Add view based on child count

private void addEditTextView() {
    if (binding.layoutList.getChildCount() <= 5) {
        View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
        EditText val1 = inputView.findViewById(R.id.input_value_1);
        binding.layoutList.addView(inputView);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM