简体   繁体   中英

Android data binding on drawable

I hv two shape drawables, rounded_corners.xml and rounded_corners_red.xml which will be used to show valid text input and invalid text input respectivly.

I want this drwable to be set dynamically when user click on login button such that if valid text show rounded_corners.xml and if invalid show rounded_corners_red.xml.

Below is how I hv put it in my layout xml.

<EditText android:id="@+id/et_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@={systemSettings.isValid ? @drawable/rounded_corners : @drawable/rounded_corners_red}"
android:text="@={systemSettings.serverIP, default=@string/ip_host}"
android:textColor="#000000" />

I want drawable to be applied dynamically based on isValid observable varible defined in my model class. My code compiles with no errors. But it gives run time error

java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:The expression ((systemSettingsIsValidGet) ? (getDrawableFromResource(etIp, R.drawable.rounded_corners)) : (getDrawableFromResource(etIp, R.drawable.rounded_corners_red))) cannot cannot be inverted: The condition of a ternary operator must be constant: android.databinding.tool.writer.KCode@429a75fd
file:D:xxx\app\src\main\res\layout\fragment_system_settings.xml
loc:92:47 - 92:128
****\ data binding error ****

Anyone knows why this happens? Thanks.

Your statement is a 2-way binding @={}

@={systemSettings.isValid ? @drawable/rounded_corners : @drawable/rounded_corners_red}`

That's why you find the error stating that the expression

cannot cannot be inverted

It even gives you the reason direcly:

The condition of a ternary operator must be constant

But since you're just getting drawable resources it's save to just remove the = from the expression.

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