调用 notifyDataSetChanged() 后如何在列表视图中设置文本

How to set text in listview after notifyDataSetChanged() has been called

场景: 我有一个 ListView,当用户点击 child 时,设置TextView 内的 ListView 通过主 activity 的值。

我有一个 FloatingActionButton,它添加和减去一个 object 来计算 ListView 中的项目数量。

要添加或减去 ListView 显示的 children 的数量,我调用 notifyDataSetChanged().

我正在尝试在调用 notifyDataSetChanged() 后将输入的文本设置回 TextView


问题: notifyDataSetChanged() 将 TextView 重置回空白 运行宁完成了。

我试过的:我试过将 ListView 项中的所有值保存到单独的 String[] savedItems 并在 TextView 中设置文本。我在调试器中 运行 一步一步地编写代码,看到代码正在保存文本并实际设置文本,但由于某种原因,notifyDataSetChanged() 尚未完成其工作。

如何在 notifyDataSetChanged() 完成后设置文本?


问题代码:

public void addNewThought(int numberOfThoughts) {
    String[] savedDistortionsList = saveDistortions(); // This saves each childs text

    selectedItems[numberOfThoughts] = new ArrayList<String>();
    IntegerNumberOfThoughts.add(Integer.toString((numberOfThoughts++)) ); // Just the variable that counts the number of children needed in ListView

    distortionsAdapter.notifyDataSetChanged(); // Refresh ListView
    setBackDistortionsList(savedDistortionsList); // Put back text into ListView
}

saveDistortions() 有效,所以我认为没有必要显示,但这是我测试过的 setBackDistortionsList() 的代码,它实际上是在 ListView 中设置 TextView 但它只是由于某种原因没有显示。

setBackDistortionsList

private void setBackDistortionsList(String[] savedDistortionsList) {
    View tempView;
    TextView tempTextView;
    for (int i = 0; i < savedDistortionsList.length; i++) {
        tempView = LDistortions.getChildAt(i);
        tempTextView = (TextView) tempView.findViewById(R.id.textEntry);
        tempTextView.setText(savedDistortionsList[i]);
    }
}

答案在这里找到:

从用户@Petro 复制并粘贴

希望这对您有所帮助:

  • 在列表视图上设置一个 addOnLayoutChangeListener
  • 调用.notifyDataSetChanged();
  • 这将在完成后触发 OnLayoutChangeListener
  • 删除侦听器
  • 更新时执行代码 (getLastVisiblePosition())

    mListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    
      @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        mListView.removeOnLayoutChangeListener(this);
        Log.e(TAG, "updated");
      }
    });
    
    mAdapter.notifyDataSetChanged();