Monday, 13 May 2019

DataBinding in MVVVM pattern using LiveData and Retrofit

In Previous example i am replacing thing using ViewBinding like following:-
1. we have to enable dataBinding in app.gradle file like following :-
dataBinding {
    enabled = true}

2. MainActivity:-
public class MainActivity extends AppCompatActivity {
    private MainActivityViewModel viewModel;
    private ActivityMainBinding binding;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);       
 binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        viewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
        getEmpDetailFromViewModel();
    }

    private void initRecyclerView(List<AlbumResponse> responses) {
        AlbumAdapter adapter = new AlbumAdapter(responses);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(manager);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setHasFixedSize(true);
    }
}

layout xml will change like following :-


2. AlbumAdapter:-
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.MyViewHolder> {
    private List<AlbumResponse> responseList;
    private AlbumListBinding binding;

    public AlbumAdapter(List<AlbumResponse> responseList) {
        this.responseList = responseList;
    }

    @NonNull    @Override    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        //View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.album_list,viewGroup,false);       
 binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),R.layout.album_list,viewGroup,false);
        return new MyViewHolder(binding);
    }

    @Override    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.listBinding.employeeName.setText(responseList.get(i).getUserId()+"");
        myViewHolder.listBinding.id.setText(responseList.get(i).getId()+"");
        myViewHolder.listBinding.employeeSalary.setText(responseList.get(i).getTitle()+"");

    }

    @Override    public int getItemCount() {
        return responseList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{
        private AlbumListBinding listBinding;
        public MyViewHolder(@NonNull AlbumListBinding itemView) {
            super(itemView.getRoot());
            listBinding = itemView;
        }
    }
}

No comments:

Post a Comment