I'm starting to use the data binding library, and for the most part, it's working just great.
However, I can't find if there's a way to "loop" over the items in a collection and use that to populate a LinearLayout.
Basically, suppose I have this:
class PersonViewModel
public List<String> emails;
end
Then in the XML I have
<LinearLayout>
<TextView
android:text="a single email">
</LinearLayout>
I want that TextView to be repeated as many times as emails I have.
Is there a simple way to do this?
public class User {
public String name;
public String phone;
public List<String> emails;}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="user"
type="com.androidbolts.databindingsample.model.User" />
</data>
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:emails="@{user}" />
</layout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
User user = new User();
List<String> emails = new ArrayList<>(5);
emails.add("email 1");
emails.add("email 2");
emails.add("email 3");
emails.add("email 4");
emails.add("email 5");
user.emails = emails;
binding.setUser(user);
}
@BindingAdapter({"bind:emails"})
public static void setEmails(LinearLayout parent, User user) {
for (int i = 0, size = user.getEmails().size(); i < size; i++) {
TextView tv = new TextView(parent.getContext());
tv.setText(user.getEmails().get(i));
parent.addView(tv);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With