简体   繁体   English

更新ListView或Activity?

[英]Update ListView or Activity?

I have a listView inside Activity inside tab layout. 我在选项卡布局内的Activity中有一个listView。 If I long press the item, I get the option to rename the item. 如果长按该项目,则可以选择重命名该项目。 Once the item is renamed, the change can't be seen until the activity is restarted. 重命名该项目后,只有重新启动活动后才能看到更改。

I tried solving the problem by simply creating a new intent and re-opening activity, but since that activity is inside tablayout it doesn't work. 我试图通过简单地创建一个新的Intent并重新打开活动来解决问题,但是由于该活动位于tablayout内部,因此无法正常工作。 I also tried re-opening tabLayout activity but then it automatically goes to tab 1, while I'm trying to refresh listView inside tab 2. 我也尝试过重新打开tabLayout活动,但随后它会自动转到选项卡1,而我试图刷新选项卡2内的listView。

So then I tried solving it by creating updateListView() method: 因此,我尝试通过创建updateListView()方法来解决它:

public void updateListView(){
    listAdapter.clear();
    listAdapter.addAll(recordedFilesArray);
    listAdapter.notifyDataSetChanged();
}

But that doesn't work either. 但这也不起作用。 When I'm using this method, it completely clears listView and then I have to restart the activity again to see the results. 当我使用这种方法时,它会完全清除listView,然后我必须再次重新启动活动才能看到结果。

So, anyone have any idea what I could do to see listView changes without restarting the activity? 因此,任何人都不知道在不重新启动活动的情况下如何查看listView的更改? By the way, if it helps, I'm reading ListView (ArrayList) from a text file. 顺便说一句,如果有帮助,我正在从文本文件中读取ListView(ArrayList)。

尝试仅使用notifyDataSetChanged()而不清除listAdapter

You can make a separate adapter class and implement its getView() function to manage this. 您可以创建一个单独的适配器类并实现其getView()函数来管理它。 Your activity will pass the array list to the adapter. 您的活动会将数组列表传递给适配器。 The adapter's getView() will take care of displaying the contents from the list. 适配器的getView()将负责显示列表中的内容。

When the list gets modified, you need to reinitialize the adapter. 修改列表后,您需要重新初始化适配器。 So that way getView() always have the updated data to display on the screen. 这样一来,getView()始终将更新后的数据显示在屏幕上。

要重命名项目,可以在ArrayList中更改项目对象,然后调用adapter.notifyDataSetChanged()

I found the problem. 我发现了问题。 The ArrayList wasn't changed until the activity was restarted. 在重新启动活动之前,不会更改ArrayList。 I had to call arrayList.set() to change the element in the ArrayList. 我必须调用arrayList.set()来更改ArrayList中的元素。 Now it works as it should. 现在它可以正常工作了。

My code: 我的代码:

recordedFilesArray.set(toDelete, input.getText().toString()); //toDelete is arg2 variable (onLongItemClickListener)
listAdapter.notifyDataSetChanged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM