I want to apply android:textAlignment to TextView using databinding like this:
android:textAlignment="@{viewModel.switcher ? START : CENTER}"
For now I've implemented it throw gravity:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@{viewModel.text}"
android:textAlignment="gravity"
android:gravity="@{viewModel.switcher ? Gravity.LEFT : Gravity.CENTER}"
android:textSize="14sp"/>
But can I implement textAlignment directly throw databinding?
This works, if you do it like this:
In your databinding layout import View and use it's alignment constants:
<layout>
<data>
<import type="android.view.View" />
</data>
<TextView
...
android:textAlignment="@{View.TEXT_ALIGNMENT_CENTER}"
... />
</layout>
You can use the following constants: View.TEXT_ALIGNMENT_INHERIT; View.TEXT_ALIGNMENT_GRAVITY; View.TEXT_ALIGNMENT_TEXT_START; View.TEXT_ALIGNMENT_TEXT_END; View.TEXT_ALIGNMENT_CENTER; View.TEXT_ALIGNMENT_VIEW_START; View.TEXT_ALIGNMENT_VIEW_END;
For more info on these constants check the documentation here.
In your particular case you could write:
<layout>
<data>
<import type="android.view.View" />
</data>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="@{viewModel.text}"
android:textAlignment="@{viewModel.switcher ? View.TEXT_ALIGNMENT_VIEW_START : View.TEXT_ALIGNMENT_CENTER}"
android:textSize="14sp"/>
</layout>
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