Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the new Android data binding library to populate the children of a LinearLayout based on a Collection?

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?

like image 394
Nacho Avatar asked Sep 08 '15 13:09

Nacho


1 Answers

Suppose your user class:

public class User {
public String name;
public String phone;
public List<String> emails;}

Now your layout file:

<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>

Now your activity class sample

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);
    }
}
}
like image 197
subhash Avatar answered Sep 28 '22 03:09

subhash