gpt4 book ai didi

java - 为什么 LiveData List 中的值更改时不调用 onChanged?

转载 作者:行者123 更新时间:2023-12-02 10:50:24 30 4
gpt4 key购买 nike

上下文

使用MutableLiveData<List<Integer>>去持有一个值(value)观。当 List 中的第一个值(为简洁起见,使用第一个值作为示例)时递增,TextView应该更新于onChanged显示 List 中的第一个值.

目标

  • 增加 List 中的第一个值
  • 更新TextViewList 的第一项时变化

问题

  1. Button单击 List 中的第一个值增加但 MutableLiveData.onChanged()没有被调用,这是为什么?
  2. MutableLiveData只回复其setValue方法?
  3. 这个问题可以通过 List 解决吗?包含MutableLiveData整数(即 MutableLiveData<List<MutableLiveData<Integer>> ,有问题,因为需要监听 List 中的每个项目)?
  4. 有更好的方法来实现目标吗?

代码

final MutableLiveData<List<Integer>> vals = new MutableLiveData<>();
List<Integer> intVals = new ArrayList<>();
intVals.add(0);
vals.setValue(intVals);

tv.setText("" + vals.getValue().get(0));

vals.observe(this, new Observer<List<Integer>>() {
@Override
public void onChanged(@Nullable List<Integer> integers) {
int firstVal = integers.get(0);
Log.d(TAG, "onChanged val " + firstVal);
tv.setText("" + firstVal);
}
});

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// first val in List is incremented but onChanged isn't called, why?
int newVal = vals.getValue().get(0) + 1;
vals.getValue().set(0, newVal);
Log.d(TAG, "set val at index 0 to " + newVal);
}
});

最佳答案

LiveData Observable 的 onChanged 方法仅在调用 setValue()postValue().setValue() 后调用> 应该仅从主线程调用,因为 postValue() 应该从不同的线程调用(onClick 发生在主线程上,因此 setValue() 将做)。无论如何,使用下面的代码将获得您所需要的:

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// first val in List is incremented but onChanged isn't called, why?
List<Integer> temp = vals.getValue();
if(temp!=null) // null-safety just in case....
{
int newVal = temp.get(0) + 1;
temp.set(0, newVal);
vals.setValue(temp);
Log.d(TAG, "set val at index 0 to " + newVal);
}
}
});

关于java - 为什么 LiveData List 中的值更改时不调用 onChanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52228071/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com