【发布时间】:2017-05-24 19:16:45
【问题描述】:
我想将我的 XML 布局转换为 Anko DSL,但 CardView 出现问题
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cardview_manga"
android:layout_margin="5dp">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/manga_cover"
android:background="@color/placeholder_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@string/cover" />
<TextView
android:id="@+id/manga_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:padding="5dp"
android:background="#3f000000"
android:textColor="#ffffff"
android:textSize="14sp" />
</FrameLayout>
</android.support.v7.widget.CardView>
这是我转换成的 Anko DSL:
class ItemManga : AnkoComponent<ViewGroup> {
companion object {
lateinit var mangaCover: ImageView
lateinit var mangaName: TextView
}
override fun createView(ui: AnkoContext<ViewGroup>) = ui.apply {
relativeLayout {
cardView {
frameLayout {
lparams {
height = matchParent
width = matchParent
}
mangaCover = imageView {
backgroundColor = R.color.placeholder_background
contentDescription = ctx.getString(R.string.cover)
}.lparams {
height = matchParent
width = matchParent
}
mangaName = textView {
textSize = sp(14).toFloat()
textColor = android.R.color.white
backgroundColor = R.color.manga_title_background
}.lparams {
height = wrapContent
width = matchParent
gravity = Gravity.BOTTOM
padding = dip(5)
}
}
}.lparams {
height = wrapContent
width = matchParent
margin = dip(5)
}
}
}.view
}
结果不是预期的:
- CardView 占位符的背景是紫色的,而它应该是灰色的。
- ImageView 与 CardView 不匹配。
- TextView背景是紫色的,太高了甚至不出现。
以下是一些截图:
【问题讨论】:
-
你如何使用它?我的意思是我对你在这里使用伴生对象有点困惑。关于颜色,您需要获取 Color 类的实例,而不是 Int - ContextCompat.getColor(context, R.color.your_desired_colour)
-
顺便说一句,你可以写
override fun createView(ui: AnkoContext<ViewGroup>) = with(ui) { relativeLayout { ... } },没有.view,还有textSize = dip(14)