具體用法
我在上一篇介紹了Kotlin的Adapter寫法,這次咱們來了解一下,Kotlin和Databinding怎么一起來寫Adapter(這里咱們只介紹recycleView了,畢竟recycleView已經很普遍了,如果listview需要,可以留言我),如圖所示:圖中已標注出與正常語法不同的地方
1.png
adapter就如上圖那樣了,剛寫的時候,會有點不習慣,多寫幾次就好了。
那下面給大家看一下xml的代碼,使用的是databinding的語法:
xml代碼演示
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data class="CollectBind">
//utils用的是kotlin語法
<import type="com.kotlin.databinding.zhihu.utils.DateFormatUtilsKT"/>
<variable
name="collectModel"
type="com.kotlin.databinding.zhihu.model.CollectRecomModel"/>
</data>
<android.support.v7.widget.CardView
android:id="@+id/news_list_card_view"
style="@style/cardStyle"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp">
<RelativeLayout
android:id="@+id/id_rl_collect"
style="@style/cardRelativeLayoutStyle"
tools:ignore="UselessParent">
<ImageView
android:id="@+id/thumbnail_image"
style="@style/cardImageViewStyle"
bind:error="@{@drawable/ic_card_overflow}"
bind:imageUrl="@{collectModel.image_url}"
bind:isShowImage="@{@bool/b_true}"
tools:background="#d71345"
/>
<TextView
android:id="@+id/question_title"
style="@style/cardQuestionTitleStyle"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/thumbnail_image"
android:layout_toLeftOf="@+id/card_share_overflow"
android:ellipsize="end"
android:maxLines="2"
android:text="@{collectModel.title}"
tools:text="我是標題我是標題我是標題我是標題我是標題我是標題我是標題我是標題"/>
<com.kotlin.databinding.zhihu.widget.TagGroup
android:id="@+id/title_label"
style="@style/TagGroup"
android:layout_alignBottom="@+id/thumbnail_image"
android:layout_toRightOf="@+id/thumbnail_image"
tools:text="label|label|label"/>
<TextView
android:id="@+id/daily_title"
style="@style/baseCardTextStyle"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/thumbnail_image"
android:gravity="bottom|right"
android:text="@{DateFormatUtilsKT.INSTANCE.stampToDate(collectModel.publication_date)}"
tools:text="我是日期"
/>
<ImageView
android:id="@+id/card_share_overflow"
android:visibility="invisible"
style="@style/cardOverflowIconStyle"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</layout>
xml內容已經全部在這里了,里面用到了databinding的一些自定義屬性,還有就是用了tools:xxx屬性來顯示默認值(這個默認值只會在xml顯示的,跑起來時,界面是不會顯示的)。如果xml有什么疑問歡迎提出來。
Adapter已經修改好了,它的用法和之前的其實是一樣的,那咱們就再寫一遍,多寫幾遍就不陌生了。
具體使用
val manager = LinearLayoutManager(this)
manager.orientation= LinearLayoutManager.VERTICAL
id_collect_recycle.layoutManager= manager
adapter= CollectDataAdapter(this,{
//這是類似Lambda表達式的寫法
position->
itemClick()
})
adapter.appendList(data)
id_collect_recycle.adapter=adapter
好了,到這里,咱們Kotlin和Databinding已經介紹完了。