我想做的是创建一个烹饪警报应用程序。
我正在使用MVVM体系结构,并希望通过LiveData更新它。
这是我的警报类别。每隔一秒钟,item
内部的所有data
将被触摸,并应调用tick
。 tick
将更新timeLeft
,应将其反映到UI上。但是,屏幕的其他组件应保持不变。
唯一定期更新的是代表剩余时间的文本(我尚未编写将代码从int转换为字符串的代码)。确保回收者视图仅更新时间并且不浪费时间重新设置图像和项目名称的最佳方法是什么?
class Alarm(item: Item, private val context: Context, val notifyID: Int) {
var timeLeft = item.timeInSec
val name = item.name
val imageUri = item.imageUri
var isFinished = false
// count down goes down every seconds
fun tick() {
timeLeft--
if (timeLeft <= 0) {
onFinish()
}
}
fun onFinish() {
isFinished = true
}
}
这里是使用LiveData,RecyclerView和ViewModel的实现。
活动:
private MyVM mVM;
private RecyclerView mRecyclerView;
private Adapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mRecyclerView = findViewById(...);
mVM = ViewModelProviders.of(this).get(MyVM.class);
mAdapter = new Adapter(mVM.getStuff().getValue(), getLayoutInflater());
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mVM.getStuff().observe(this, stuff -> {
mAdapter.setItems(stuff);
});
}
static class Adapter extends RecyclerView.Adapter<Adapter.VH> {
private // list items ;
private LayoutInflater mInflater;
Adapter(..., LayoutInflater i) {
...
mInflater = i;
}
@NonNull
@Override
public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new VH(mInflater.inflate(R.layout.item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull VH holder, int position) {
//set views in holder
}
@Override
public int getItemCount() {
//return size of the collection
}
public void setItems(...) {
// update with diffutil
notifyDataSetChanged();
}
static class VH extends RecyclerView.ViewHolder{
// views
VH(View v){
super(v);
...
}
}
}
ViewModel:
public class MyVM extends ViewModel {
private MutableLiveData<...> stuff;
public MyVM(){
// initialize and mutate stuff
}
public LiveData<...> getStuff(){
return getStuff;
}
}