Android MVVM with Programmatic UI Customization -
i'm trying nail down proper mvvm layering in app android data binding lib. simple layouts, in examples, abstract nicely xml layouts binding methods in view model event handling , model updates via observables. however, more not, there's ui customization needs done programmatically (findviewbyid()...) and/or through things injecting styling attributes string resources.
should treat activity/fragment part of view , whatever can't handled between vm , layout via databinding, or better handle interface vm activity/fragment (while trying keep vm pojo)?
-- edit: example1 --
rendering textview multiple colors in same string: how had implemented wrapping cdata , font tags in string resource , rendering findviewbyid().settext(html.fromhtml(getstring(..))). i've modified layout instead bind in vm android:text="@{viewmodel.text1}", calls interface method fragment returns html.fromhtml(text), , vm returns spanned layout. thinking strict mvvm, wouldn't define vm way feels little hacky.
as rule of thumb not put viewmodel needs android context. on other hand logic should located in viewmodel can unit test it.
for example if want textview display either string or b depending on decision made in viewmodel can create interface abstraction of android resources , pass interface view viewmodel.
public myviewmodel { private mystrings strings; public myviewmodel(mystrings strings) { this.strings = strings; } public string getmystring() { return becauseofreasons() ? strings.geta() : strings.getb(); } public interface mystrings { string geta(); string getb(); } }
for example wanted use html.fromhtml programmatically. what's great android databinding library can use access html.fromhtml() xml. in case xml this:
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <import type="android.text.html"/> <variable name="viewmodel" type="some.package.myviewmodel"/> </data> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{html.fromhtml(viewmodel.mystring)}"/> </layout>
however pretty radical approach. recommend consider if viewmodel remains testible. example can still create junit tests when access resource ids r class in viewmodel. on other hand should not use html.fromhtml in viewmodel because, not mocked error.
Comments
Post a Comment