简体   繁体   中英

Android data binding nested ternary on expression

In android's data binding syntax is there anyway to do a nested ternary on the result of an expression without calculating the expression twice:

For the single ternary case I have the following:

android:textColor="@{stock.mStockDelta.compareTo(BigDecimal.ZERO) < 0 ?
                   @color/red : @color/green}"

I'm wondering if there's a way I can set the color for each one of three compareTo results {-1, 0, 1} just using the xml?

Possible duplicate ( Switch case in Data Binding )

For the advanced logic in the data binding, you should put your own logic into the method and call it in the xml

android:textColor="@{stock.mStockDelta.getColor}"

Do your own logic in the getColor method instead of put a lot of condition in the xml. You should remain your xml fully-readable. Leave the logic flow for the java class.

 android:textColor="@{stock.mStockDelta.getColor > 2 ?( stock.mStockDelta.getColor ==3 ? @color/green :@color/colorPrimary): @color/colorAccent }"

you can try this

android:textColor="@{stock.mStockDelta.compareTo(BigDecimal.ZERO) < 0 ?
               @color/red : (stock.mStockDelta.compareTo(BigDecimal.ZERO) > 0 ? @color/green : @color/blue)}"

But this is not recommended, you should put this logic in view model as George Mount suggested in this comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM