持有人发生事情时更新RecyclerView

时间:2019-07-11 19:01:47

标签: java android android-fragments android-recyclerview

所以,这是我的项目结构。这只是一个两个选项卡的应用程序。

在左侧标签上,有所有可用项目的列表。在右侧的标签上,有一个用户收藏夹项目的列表。在每个项目中,都有一个单击按钮,然后该项目成为收藏夹。好吧,至少那是我想要实现的。显然,这些项目已添加到“收藏夹”列表中,但目前查看新收藏夹列表的唯一方法是关闭并重新打开应用程序。

我需要一种方法来将项目添加为收藏夹时调用adapter.notifyDataSetChanged()

现在,此最喜欢的功能是通过我使用的Holder中的一种方法完成的。因此,基本上,用户单击了项目上的收藏按钮,然后Holder有一个clickListener,它更新了我作为 JSON 存储在SharedPreferences中的数组,该数组包含所有收藏夹项目。

这两个选项卡是片段,每个片段都有一个RecyclerView。它们都使用相同的类:

public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    private PageViewModel pageViewModel;

    private int section;

    private RecyclerView recyclerView;

    private SharedPreferences prefs = null;

    public static PlaceholderFragment newInstance(int index) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_SECTION_NUMBER, index);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }

        section = index;
        pageViewModel.setIndex(index);
        prefs = getContext().getSharedPreferences("app_preferences", MODE_PRIVATE);
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView = rootView.findViewById(R.id.items_list);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
        recyclerView.addItemDecoration(dividerItemDecoration);

        recyclerView.setLayoutManager(linearLayoutManager);

        List<ItemModel> itemList= new ArrayList<>();

        // All Items Tab
        if (section == 1) {
            // Here I get all the Items and set them in the itemList Array

        else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)
            Gson gson = new Gson();
            String json = prefs.getString("favoriteList", "");

            if (json.isEmpty()) {

            } else {
                Type type = new TypeToken<List<ItemModel>>() {
                }.getType();

                itemList= gson.fromJson(json, type);
            }
        }

        MyItemAdapter itemAdapter = new MyItemAdapter (getContext(), getActivity(), itemList, section);

        recyclerView.setAdapter(itemAdapter);

        return rootView;
    }

2 个答案:

答案 0 :(得分:1)

您可以使用MutableLiveData来观察列表,然后可以在observe块内调用adapter.notifyDataSetChanged()。 例如,

public class PlaceholderFragment extends Fragment {

    private MutableLiveData<List<ItemModel>> mMutableLiveData;

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        mMutableLiveData = new MutableLiveData<>();
        mMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
               rootView.findViewById(R.id.items_list).getAdapter().notifyDataSetChanged();
            }
        });

        List<ItemModel> itemList= new ArrayList<>();

        // All Items Tab
        if (section == 1) {
            // Here I get all the Items and set them in the itemList Array

        else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)
            Gson gson = new Gson();
            String json = prefs.getString("favoriteList", "");

            if (json.isEmpty()) {

            } else {
                Type type = new TypeToken<List<ItemModel>>() {
                }.getType();

                itemList= gson.fromJson(json, type);
                mMutableLiveData.setValue(itemList);
            }
        }

        MyItemAdapter itemAdapter = new MyItemAdapter (getContext(), getActivity(), itemList, section);

        recyclerView.setAdapter(itemAdapter);

        return rootView;
    }
}

答案 1 :(得分:0)

由于您已经在使用SharedPreferences来保存收藏夹列表,因此可以在其上注册侦听器以在更新时进行更新,然后可以从SharedPreferences检索这些更改,然后更新列表。 / p>

在片段的onCreateView()方法中,您检查此条件:

// All Items Tab
    if (section == 1) {
        // Here I get all the Items and set them in the itemList Array

    else { // Favorite Items Tab (it retrieves an array of items stored in the SharedPreferences)

        pref.unregisterOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener(){
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key){
                // here you can retrieve updated data from SharedPreferences and update your list
            }
        });

        Gson gson = new Gson();
        String json = prefs.getString("favoriteList", "");

        if (json.isEmpty()) {

        } else {
            Type type = new TypeToken<List<ItemModel>>() {
            }.getType();

            itemList= gson.fromJson(json, type);
        }
    }