通过MVVM方法使用DataBinding和ViewModel创建RecycleView Adapter

时间:2018-12-01 01:48:40

标签: android mvvm data-binding viewmodel

我想借助RecyclerListview方法借助数据绑定&ViewModelMVVM中显示数据。在我的XML中创建了View Model类的数据变量,但是在声明的适配器类中出现错误

holder.chatlistitemBinding.setChatlistVM(mChatList.get(position)); 

因为mChatList.get(position)ChatList模型而不是ViewModel的数组。我该如何纠正?请不要建议更改指向模型类(ChatList)的数据变量。我想通过视图模型实现MVVM方法。预先感谢。

我的XML文件:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
>
    <data >
    <variable name="handlers" type="com.support.android.designlibdemo.View.Handlers.ChatListHandlers"/>

      <variable name="chatlistVM" type="com.support.android.designlibdemo.ViewModel.ChatListViewModel" />
    </data>
    <RelativeLayout
    .......

            <TextView
                android:id="@+id/placeholder2"

                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{chatlistVM.chatList.first_name}"
                android:textAppearance="?android:attr/textAppearanceSmall" 
      />
            ...
</layout>

适配器类别:

public class AdapterChatList extends RecyclerView.Adapter<AdapterChatList.ChatListViewHolder> {
    private LayoutInflater mInflater;
    private static final String TAG = "ChatListAdapter";
    public List<ChatListViewModel> mChatList = new ArrayList<>();
    public AdapterChatList(Context context) {
    mInflater = LayoutInflater.from(context);
    }
    class ChatListViewHolder extends RecyclerView.ViewHolder{

    private ChatlistitemBinding chatlistitemBinding;
    public ChatListViewHolder(ChatlistitemBinding itemBinding) {
        super(itemBinding.getRoot());
        chatlistitemBinding = itemBinding;
    }

    }

    @NonNull
    @Override
    public ChatListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    if (mInflater == null) { mInflater = LayoutInflater.from(parent.getContext()); }
    ChatlistitemBinding chatListUserItemBinding = DataBindingUtil.inflate(mInflater, R.layout.chatlistitem, parent, false);
    return new ChatListViewHolder(chatListUserItemBinding);
    }
    @Override
    public void onBindViewHolder(@NonNull ChatListViewHolder holder, int position) {
    holder.chatlistitemBinding.setChatlistVM(mChatList.get(position));
    holder.chatlistitemBinding.setHandlers(new ChatListHandlers());
    holder.chatlistitemBinding.executePendingBindings();
    }
    @Override
    public int getItemCount() {
    if (mChatList != null)
        return mChatList.size();
    else return 0;
    }

    void add(ChatList chatList) {
        mChatList.add(chatList);
        notifyItemInserted(getItemCount());
    }
    public void updatelist(List<ChatList> userlist){//Need to rethink on this method
    mChatList = userlist;
    notifyDataSetChanged();
    }
}

ViewModel:

public class ChatListViewModelextends AndroidViewModel {

    private ChatList chatList ;

    public ChatListViewModel(Application application){
        super(application);
        chatList = new ChatList();

    }

}

2 个答案:

答案 0 :(得分:1)

在这种情况下,我不会扩展框架提供的ViewModel类,因为您只想将ViewModel绑定到特定视图。

因此解决方案很简单: 将chatList作为VM的构造函数参数,然后将其设置为 holder.chatlistitemBinding.setChatlistVM(new ChatListViewModel(mChatList.get(position)));

答案 1 :(得分:0)

工厂类:

  @Suppress("UNCHECKED_CAST")
class Factory @Inject constructor(
    private val chatList: ChatList
) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ChatListViewModel::class.java)) {
            return ChatListViewModel(chatList) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.canonicalName}")
    }

}

然后您以相同的方式获得虚拟机,只需传递Factory实例 例如,从您的FragmentFragmentActivity中,您会致电:

viewModel = ViewModelProviders.of(this, viewModelFactory).get(ChatListViewModel:class.java);