Обновляйте RecyclerView, когда что-то происходит в держателе - PullRequest
0 голосов
/ 11 июля 2019

Итак, вот моя структура проекта. Это просто приложение с двумя вкладками.

На левой вкладке есть список всех доступных предметов. На правой вкладке есть список любимых предметов пользователя. В каждом элементе есть кнопка, по которой вы нажимаете, и затем этот элемент становится любимым. Ну, по крайней мере, это то, чего я хочу достичь. Очевидно, что элементы добавляются в список избранного, но на данный момент единственный способ увидеть новый список избранного - закрыть и снова открыть приложение.

Что мне нужно, так это как-то назвать adapter.notifyDataSetChanged(), когда элемент добавлен в избранное.

Прямо сейчас, эта любимая функциональность сделана в качестве метода от держателя, который я использую. Таким образом, в основном пользователь нажимает кнопку избранного на элементе, а затем у Держателя есть 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 ]

1 голос
/ 11 июля 2019

Вы можете использовать MutableLiveData для наблюдения за своим списком, затем вы можете вызвать 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;
    }
}
0 голосов
/ 11 июля 2019

Поскольку вы уже используете SharedPreferences для сохранения списка избранных, вы можете зарегистрировать прослушиватель в нем, чтобы получать обновления при каждом его обновлении, а затем вы можете получить эти изменения из SharedPreferences и затем обновить свой список.

В методе 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);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...