android studio开发中怎么将一个图标样式与一个布尔变量绑定
时间: 2023-04-09 11:03:52 浏览: 183
你可以使用 Android Data Binding 来将一个图标样式与一个布尔变量绑定。具体步骤如下:
1. 在 build.gradle 文件中添加以下依赖:
```
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
implementation 'com.android.databinding:library:1.4.0'
}
```
2. 在布局文件中使用 data 标签来声明变量和表达式:
```
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="isLiked"
type="Boolean" />
</data>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@{isLiked ? @drawable/ic_liked : @drawable/ic_unliked}" />
</layout>
```
3. 在 Activity 或 Fragment 中使用 DataBindingUtil 绑定布局和数据:
```
val binding: LayoutBinding = DataBindingUtil.setContentView(this, R.layout.layout)
binding.isLiked = true
```
这样,当 isLiked 变量为 true 时,ImageView 的 src 属性会绑定到 ic_liked 图标;当 isLiked 变量为 false 时,ImageView 的 src 属性会绑定到 ic_unliked 图标。
阅读全文
相关推荐


















