Android初学第82天
Posted HankZhou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android初学第82天相关的知识,希望对你有一定的参考价值。
android初学第82天
20_MVVM
代码
BeatBox
BeatBoxFragment.java
package com.bignerdranch.android.beatbox;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.android.beatbox.databinding.FragmentBeatBoxBinding;
import com.bignerdranch.android.beatbox.databinding.ListItemSoundBinding;
import java.util.List;
public class BeatBoxFragment extends Fragment {
private BeatBox mBeatBox;
public static BeatBoxFragment newInstance() {
return new BeatBoxFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentBeatBoxBinding binding = DataBindingUtil
.inflate(inflater, R.layout.fragment_beat_box, container, false);
binding.recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
binding.recyclerView.setAdapter(new SoundAdapter(mBeatBox.getSounds()));
return binding.getRoot();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBeatBox = new BeatBox(getActivity());
}
private class SoundHolder extends RecyclerView.ViewHolder {
private ListItemSoundBinding mBinding;
private SoundHolder(ListItemSoundBinding binding) {
super(binding.getRoot());
mBinding = binding;
mBinding.setViewModel(new SoundViewModel(mBeatBox));
}
public void bind(Sound sound) {
mBinding.getViewModel().setSound(sound);
mBinding.executePendingBindings();
}
}
private class SoundAdapter extends RecyclerView.Adapter<SoundHolder> {
private List<Sound> mSounds;
public SoundAdapter(List<Sound> sounds) {
mSounds = sounds;
}
@Override
public SoundHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
ListItemSoundBinding binding = DataBindingUtil
.inflate(inflater, R.layout.list_item_sound, parent, false);
return new SoundHolder(binding);
}
@Override
public void onBindViewHolder(SoundHolder holder, int position) {
Sound sound = mSounds.get(position);
holder.bind(sound);
}
@Override
public int getItemCount() {
return mSounds.size();
}
}
}
以上是关于Android初学第82天的主要内容,如果未能解决你的问题,请参考以下文章