Итак, вот моя структура проекта. Это просто приложение с двумя вкладками.
На левой вкладке есть список всех доступных предметов. На правой вкладке есть список любимых предметов пользователя. В каждом элементе есть кнопка, по которой вы нажимаете, и затем этот элемент становится любимым. Ну, по крайней мере, это то, чего я хочу достичь. Очевидно, что элементы добавляются в список избранного, но на данный момент единственный способ увидеть новый список избранного - закрыть и снова открыть приложение.
Что мне нужно, так это как-то назвать 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;
}