在片段之间切换时保存列表视图项目

问题描述 投票:0回答:1

我正在构建聊天应用程序。我有一个ChannelFragment,其中包含可以通过按按钮填充的频道列表视图。当我单击一个项目时,我移到另一个名为MessageFragment的片段,其中包含来自该频道的聊天。但是,当我使用导航栏导航到ChannelFragment时,整个列表视图将刷新,并且没有任何内容。

切换到消息片段后,如何在列表视图中保存创建的项目?谢谢。

我的ChannelFragment中的列表视图

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    channelList = new ArrayList<>();

    Bundle bundle = getArguments();
    if (bundle != null) {
        nick = bundle.getString("nick");
        channel = bundle.getString("channel");
    }

    channelList.add(new Channel(channel, "0 people"));

    channelListView = getView().findViewById(R.id.channelListView);
    adapter = new ChannelListAdapter(getActivity(), R.layout.adapter_view_channel_layout, channelList);
    channelListView.setAdapter(adapter);

    channelListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            Channel item = adapter.getItem(position);
            Bundle messageBundle = new Bundle();
            messageBundle.putString("nick",nick);
            messageBundle.putString("channel",item.getChannelName());
            MessageFragment messageFragment = new MessageFragment();
            messageFragment.setArguments(messageBundle);

            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.layout_for_fragments, messageFragment, "MessageF").commit();
        }
    });


}

我如何导航到它

  @Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

    int id = menuItem.getItemId();

    if (id == R.id.channels) {
        ChannelFragment channelFragment = new ChannelFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.layout_for_fragments, channelFragment, "Channel Fragment");
        fragmentTransaction.commit();
    }

第一个图片是我创建商品时的图片,第二个图片是我从消息片段中导航回来的时候When I create the list view

When I come back to it from the message fragment

android
1个回答
1
投票

此答案分为两部分

1),因为每次调用channelList = new ArrayList<>();时,您在onViewCreated中的onViewCreated都将清除列表。此时不要创建新列表,在将变量定义为类的成员时创建空列表,例如定义channelList变量的类型的位置。

当切换到新的片段时,通常会将旧的片段实例放到后台,然后在返回时重新使用。

[C0中的new正在清除当前从堆栈返回的列表。

例如代码将类似于

onViewCreated

2)使您public class ChannelFragment extends Fragment { private ArrayList<Channel> channelList = new ArrayList<>(); .... 对象可拆分

教程Channel

然后您可以使用https://www.vogella.com/tutorials/AndroidParcelable/article.htmlonSaveInstanceState()

如果片段被破坏,则使用onRestoreInstanceState()writeParcelableList存储通道列表

请参见writeTypedList

© www.soinside.com 2019 - 2024. All rights reserved.