I’ve added a linear layout with id layoutToExpend
and a button with id buttonToAdd
in my activity_main.xml. I created another layout, layout_to_copy.xml where the EditText is defined which will be added on button click in the main activity inside layoutToExpend
.
So here is my code in the MainActivity.java,
butttonToAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View newEditTexts = getLayoutInflater().inflate(R.layout.layout_to_copy,null,false);
layoutToExpend.addView(newEditTexts);
}
});
with this code whenever I click the button a new EditText is added. Now I want to write something in the added EditTexts and show them in a TextView in a new activity (Suppose, by clicking a new button Send Data
.
How to do that could anyone kindly explain, I’m new to android studio and java.
3
Answers
This is not a nice approach, try using recyclerview but if you don’t want to use it then whenever you are leaving the current activity A say on a button click then try run a for loop on linearlayout child items like this:
Now you get the values in those edittext and append in any string and pass it in bundle to next activity.
You can solve this problem in a couple of ways. From the moment that you don’t have a static amount of data source, you need to use an ArrayList or something similar. You didn’t specified, so I’ll assume that all the data that you have is of type String.
First of all, you have to declare the ArrayList, like this:
Now that you declared the list, you have to populate it. You can do it this way:
Now you have to pass the data between activity. For this, there are quite a few ways to do it. You have to choose the right way for you, here I’m going to show you two different ways, for two different cases. Please note that all the following solutions don’t implement persistent data, so you’ll lost every data when you close your app.
Here an example:
Now, in order to SET data, you have to do this:
Now, to retrieve the data stored in YourDataManager, do the following:
For taking the value from edit text. there is a couple of ways.
1/ If your edit text is limited. like user can add 5 edit text by tapping the add button. then you can create 5 edit texts in your XML layour file. and make their visibility "gone". every time you tap the add button one edit text will be visible.
so now you can define their id and take value by those ids.
2/ If your edit text is unlimited. then you can use a recycler view to add new edit text. so now you have the position id of the new edit text item by which you can get the value of edit text.