使用数据绑定将viewmodel绑定到recyclerview item.xml,android?

使用数据绑定将viewmodel绑定到recyclerview item.xml,android?,android,kotlin,android-recyclerview,data-binding,viewmodel,Android,Kotlin,Android Recyclerview,Data Binding,Viewmodel,我想在xml布局文件中绑定来自viewmodel的适配器上的数据 这是我的片段类 class NotificationFragment : Fragment() { var customeProgressDialog: CustomeProgressDialog? = null private val appPreferences: AppPreference by inject() private val notificationViewModel: NotificationViewModel

我想在xml布局文件中绑定来自viewmodel的适配器上的数据

这是我的片段类

class NotificationFragment : Fragment() {
var customeProgressDialog: CustomeProgressDialog? = null
private val appPreferences: AppPreference by inject()
private val notificationViewModel: NotificationViewModel by viewModel()
private lateinit var binding: FragmentNotificationBinding

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = FragmentNotificationBinding.inflate(inflater, container, false)
    return binding.getRoot()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.notification.layoutManager=LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
    customeProgressDialog = CustomeProgressDialog(activity)
    notificationViewModel.notifications(
        appPreferences.getUsername(),
        appPreferences.getPassword(),
        appPreferences.getUserId()
    )
    initObservables()
}

private fun initObservables() {
    notificationViewModel.progressDialog?.observe(this, Observer {
        if (it!!) customeProgressDialog?.show() else customeProgressDialog?.dismiss()
    })
    notificationViewModel.apiResponse?.observe(
        viewLifecycleOwner,
        androidx.lifecycle.Observer { response ->
            if (response.dataList != null) {
                var notificationAdapter = NotificationAdapter(response.dataList as List<Data>)
                notificationAdapter.notifyDataSetChanged()
                binding.notification.adapter = notificationAdapter
            }
        })
}
}
class NotificationFragment:Fragment(){
var customeProgressDialog:customeProgressDialog?=null
private val appPreferences:AppPreference by inject()
private val notificationViewModel:notificationViewModel by viewModel()
私有lateinit变量绑定:FragmentNotificationBinding
覆盖创建视图(
充气器:布局充气器,容器:视图组?,
savedInstanceState:捆绑?
):查看{
绑定=碎片通知绑定。充气(充气机、容器、假)
返回binding.getRoot()
}
覆盖已创建的视图(视图:视图,保存状态:捆绑?){
super.onViewCreated(视图,savedInstanceState)
binding.notification.layoutManager=LinearLayoutManager(活动,LinearLayoutManager.VERTICAL,false)
customeProgressDialog=customeProgressDialog(活动)
notificationViewModel.notifications(
appPreferences.getUsername(),
appPreferences.getPassword(),
appPreferences.getUserId()
)
initObservables()
}
私人娱乐项目{
notificationViewModel.progressDialog?观察(此,观察者{
如果(it!!)customeProgressDialog?.show()否则customeProgressDialog?.discouse()将
})
notificationViewModel.apiResponse?观察(
viewLifecycleOwner,
androidx.lifecycle.Observer{response->
if(response.dataList!=null){
var notificationAdapter=notificationAdapter(response.dataList作为列表)
notificationAdapter.notifyDataSetChanged()
binding.notification.adapter=notificationAdapter
}
})
}
}
我的视图模型

class NotificationViewModel(networkCall: NetworkCall) : ViewModel(),
Callback<ApiResponse> {
var progressDialog: SingleLiveEvent<Boolean>? = null
var apiResponse: MutableLiveData<ApiResponse>? = null
var networkCall: NetworkCall;
init {
    progressDialog = SingleLiveEvent<Boolean>()
    apiResponse = MutableLiveData<ApiResponse>()
    this.networkCall = networkCall
}

fun notifications(username: String?, password: String?, userId: String?) {
    progressDialog?.value = true
    val apiPost = ApiPost()
    apiPost.userName = username
    apiPost.password = password
    apiPost.UserId = userId
    apiPost.FileType = NetworkConstant.FILE_TYPE_NOT
    networkCall.getPDF(apiPost).enqueue(this)
}

override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
    progressDialog?.value = false
}

override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
    progressDialog?.value = false
    apiResponse?.value = response.body()
}
}
class NotificationViewModel(networkCall:networkCall):ViewModel(),
回拨{
var progressDialog:SingleLiveEvent?=null
var apiResponse:MutableLiveData?=null
var networkCall:networkCall;
初始化{
progressDialog=SingleLiveEvent()
apiResponse=MutableLiveData()
this.networkCall=networkCall
}
有趣的通知(用户名:String?,密码:String?,用户名:String?){
progressDialog?.value=true
val apiPost=apiPost()
apiPost.userName=用户名
apiPost.password=密码
apiPost.UserId=UserId
apiPost.FileType=NetworkConstant.FILE\u类型\u非
networkCall.getPDF(apiPost).enqueue(this)
}
覆盖失效时的乐趣(调用:调用,t:可丢弃){
progressDialog?.value=false
}
覆盖fun onResponse(调用:调用,响应:响应){
progressDialog?.value=false
apiResponse?.value=response.body()
}
}
适配器类

lass NotificationAdapter(private val list: List<Data>) :
RecyclerView.Adapter<NotificationAdapter.ViewHolder>() {


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val view = inflater.inflate(R.layout.element_list, parent, false)
    return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val movie: Data = list[position]
    holder.bind(movie)
    holder.itemView.setOnClickListener {

        if (!TextUtils.isEmpty(movie.filePath)) {
            try {
                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(movie.filePath))
                holder.itemView.context.startActivity(browserIntent)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }
}

override fun getItemCount(): Int = list.size

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(movie: Data) {
        with(itemView) {
            tv_notifi.text = movie.displayName
            tv_date.text = movie.UpdatedDate
            if (movie.description != null) {
                tv_brief.text = movie.description
                tv_brief.visibility = View.VISIBLE
            }
        }
    }
}

}
lass NotificationAdapter(私有val列表:列表):
RecyclerView.Adapter(){
override onCreateViewHolder(父级:ViewGroup,viewType:Int):ViewHolder{
val inflater=LayoutInflater.from(parent.context)
val视图=充气机。充气(R.layout.element_列表,父项,false)
返回视图保持器(视图)
}
覆盖BindViewHolder(holder:ViewHolder,位置:Int){
val电影:数据=列表[位置]
固定器绑定(电影)
holder.itemView.setOnClickListener{
如果(!TextUtils.isEmpty(movie.filePath)){
试一试{
val browserIntent=Intent(Intent.ACTION\u视图,Uri.parse(movie.filePath))
holder.itemView.context.startActivity(浏览器内容)
}捕获(e:例外){
e、 printStackTrace()
}
}
}
}
重写getItemCount():Int=list.size
内部类ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
趣味绑定(电影:数据){
使用(项目视图){
tv\u notifi.text=movie.displayName
tv_date.text=movie.updateDate
if(movie.description!=null){
tv_brief.text=movie.description
tv_brief.visibility=View.VISIBLE
}
}
}
}
}
这是我的项目xml布局

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="viewmodel"
        type="com.mountmeru.viewmodel.NotificationViewModel" />
</data>

<androidx.cardview.widget.CardView
    android:id="@+id/main_cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/main_cardrl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/rl_newsdate"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.3">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_notifi"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="10dp"
                android:maxLines="2"
                android:text="hey i am notification text"
                android:textColor="@android:color/black"
                android:textSize="16sp" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_brief"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_notifi"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:visibility="gone" />

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tv_brief"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="2dp"
                android:layout_marginRight="10dp"
                android:maxLines="1"
                android:text="hey i am date"
                android:textColor="@color/inactive_text"
                android:textSize="14sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/rl_newsdate"
            android:layout_weight="0.7"
            android:padding="5dp">

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/iv_notifi"
                android:layout_width="match_parent"
                android:layout_height="75dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:src="@drawable/mer" />

        </RelativeLayout>

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.cardview.widget.CardView>
</layout>


我能够为片段进行绑定,但对于适配器,我不确定如何继续。

如果我正确理解了您的问题,您希望将数据传递到xml内部的适配器。为此,您需要为您的RecyclerView编写自定义绑定适配器。 这个链接有你所需要的一切。

如果我正确理解了您的问题,您希望将数据传递到xml内部的适配器。为此,您需要为您的RecyclerView编写自定义绑定适配器。 这个链接有你所需要的一切。