jeudi 16 juin 2016

Where do I set margin, columnWeight, and rowWeight in xml that is inflated via databinding to go in a GridLayout?

Using the android-databinding library, I have the following layout XML:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:custom="http://schemas.android.com/apk/res-auto">
  <data>
    <variable [...] />
  </data>
  <GridLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="fill"
      android:layout_rowWeight="1"
      android:layout_columnWeight="1"
      android:layout_margin="2dp"
      >
[...]

I inflate this in a loop, once per instance of a model class. The inflated layout then goes in another GridLayout, which is why it has rowWeight and columnWeight. But these attributes seem to have no effect. Rather, I seem to have to set weight like so:

float weight = 1f;
int margin = 2;
XBinding ocb = XBinding.inflate(getLayoutInflater(), outerGridLayout, false);
ocb.setX(xInstances[i]);
GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
    GridLayout.spec(i/nbrColumns, weight), GridLayout.spec(i%nbrColumns, weight));
lp.setMargins(margin, margin, margin, margin);
outerGridLayout.addView(ocb.getRoot(), lp);

It seems like I shouldn't have to set the weights and the margins in the Java code. These are declarative properties of the child GridLayout, and do not vary. I assume that the properties set in the XML are not recognized because that XML file doesn't know that it's going to end up in another GridLayout until runtime. Is there a way to tell it that it is?

Or is there a more pure way to use databinding so that I rely entirely on the XML without writing the code to inflate XBinding at runtime?

Aucun commentaire:

Enregistrer un commentaire