Search in sources :

Example 1 with MainActivity

use of xyz.zedler.patrick.grocy.activity.MainActivity in project grocy-android by patzly.

the class ProductOverviewBottomSheet method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    activity = (MainActivity) requireActivity();
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
    pluralUtil = new PluralUtil(activity);
    ProductOverviewBottomSheetArgs args = ProductOverviewBottomSheetArgs.fromBundle(requireArguments());
    boolean showActions = args.getShowActions();
    if (args.getProductDetails() != null) {
        productDetails = args.getProductDetails();
        product = productDetails.getProduct();
        stockItem = new StockItem(productDetails);
    } else if (args.getStockItem() != null) {
        stockItem = args.getStockItem();
        quantityUnit = args.getQuantityUnit();
        location = args.getLocation();
        product = stockItem.getProduct();
    }
    // WEB REQUESTS
    dlHelper = new DownloadHelper(activity, TAG);
    // VIEWS
    refreshItems();
    binding.textName.setText(product.getName());
    // TOOLBAR
    boolean isInStock = stockItem.getAmountDouble() > 0;
    MenuCompat.setGroupDividerEnabled(binding.toolbar.getMenu(), true);
    // disable actions if necessary
    binding.toolbar.getMenu().findItem(R.id.action_consume_all).setEnabled(isInStock);
    binding.toolbar.getMenu().findItem(R.id.action_consume_spoiled).setEnabled(isInStock && product.getEnableTareWeightHandlingInt() == 0);
    binding.toolbar.setOnMenuItemClickListener(item -> {
        if (item.getItemId() == R.id.action_add_to_shopping_list) {
            navigateDeepLink(R.string.deep_link_shoppingListItemEditFragment, new ShoppingListItemEditFragmentArgs.Builder(Constants.ACTION.CREATE).setProductId(String.valueOf(product.getId())).build().toBundle());
            dismiss();
            return true;
        } else if (item.getItemId() == R.id.action_consume_all) {
            activity.getCurrentFragment().performAction(Constants.ACTION.CONSUME_ALL, stockItem);
            dismiss();
            return true;
        } else if (item.getItemId() == R.id.action_consume_spoiled) {
            activity.getCurrentFragment().performAction(Constants.ACTION.CONSUME_SPOILED, stockItem);
            dismiss();
            return true;
        } else if (item.getItemId() == R.id.action_edit_product) {
            String productId = String.valueOf(product.getId());
            navigateDeepLink(R.string.deep_link_masterProductFragment, new MasterProductFragmentArgs.Builder(Constants.ACTION.EDIT).setProductId(productId).build().toBundle());
            dismiss();
            return true;
        }
        return false;
    });
    Chip chipConsume = view.findViewById(R.id.chip_consume);
    chipConsume.setVisibility(isInStock ? View.VISIBLE : View.GONE);
    chipConsume.setOnClickListener(v -> {
        NavHostFragment.findNavController(this).navigate(ProductOverviewBottomSheetDirections.actionProductOverviewBottomSheetDialogFragmentToConsumeFragment().setCloseWhenFinished(true).setProductId(String.valueOf(product.getId())));
        dismiss();
    });
    Chip chipPurchase = view.findViewById(R.id.chip_purchase);
    chipPurchase.setOnClickListener(v -> {
        NavHostFragment.findNavController(this).navigate(ProductOverviewBottomSheetDirections.actionProductOverviewBottomSheetDialogFragmentToPurchaseFragment().setCloseWhenFinished(true).setProductId(String.valueOf(product.getId())));
        dismiss();
    });
    Chip chipTransfer = view.findViewById(R.id.chip_transfer);
    chipTransfer.setVisibility(isInStock && product.getEnableTareWeightHandlingInt() == 0 ? View.VISIBLE : View.GONE);
    chipTransfer.setOnClickListener(v -> {
        NavHostFragment.findNavController(this).navigate(ProductOverviewBottomSheetDirections.actionProductOverviewBottomSheetDialogFragmentToTransferFragment().setCloseWhenFinished(true).setProductId(String.valueOf(product.getId())));
        dismiss();
    });
    Chip chipInventory = view.findViewById(R.id.chip_inventory);
    chipInventory.setOnClickListener(v -> {
        NavHostFragment.findNavController(this).navigate(ProductOverviewBottomSheetDirections.actionProductOverviewBottomSheetDialogFragmentToInventoryFragment().setCloseWhenFinished(true).setProductId(String.valueOf(product.getId())));
        dismiss();
    });
    if (!showActions) {
        view.findViewById(R.id.container_chips).setVisibility(View.GONE);
    }
    // DESCRIPTION
    Spanned description = product.getDescription() != null ? Html.fromHtml(product.getDescription()) : null;
    description = (Spanned) TextUtil.trimCharSequence(description);
    if (description != null && !description.toString().isEmpty()) {
        binding.cardDescription.setText(description.toString());
    } else {
        binding.cardDescription.setVisibility(View.GONE);
    }
    if (!showActions) {
        // hide actions when set up with productDetails
        binding.linearActionContainer.setVisibility(View.GONE);
        // set info menu
        binding.toolbar.getMenu().clear();
        binding.toolbar.inflateMenu(R.menu.menu_actions_product_overview_info);
    }
    refreshButtonStates(false);
    binding.buttonConsume.setOnClickListener(v -> {
        disableActions();
        activity.getCurrentFragment().performAction(Constants.ACTION.CONSUME, stockItem);
        dismiss();
    });
    binding.buttonOpen.setOnClickListener(v -> {
        disableActions();
        activity.getCurrentFragment().performAction(Constants.ACTION.OPEN, stockItem);
        dismiss();
    });
    // tooltips
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        binding.buttonConsume.setTooltipText(activity.getString(R.string.action_consume_one, quantityUnit.getName(), product.getName()));
        binding.buttonOpen.setTooltipText(activity.getString(R.string.action_open_one, quantityUnit.getName(), product.getName()));
    // TODO: tooltip colors
    }
    // no margin if description is != null
    if (description != null) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 0, 0, 0);
        binding.linearAmount.setLayoutParams(layoutParams);
    }
    if (activity.isOnline() && !hasDetails()) {
        dlHelper.getProductDetails(product.getId(), details -> {
            productDetails = details;
            stockItem = new StockItem(productDetails);
            refreshButtonStates(true);
            refreshItems();
            loadPriceHistory();
        }).perform(dlHelper.getUuid());
    } else if (activity.isOnline() && hasDetails()) {
        loadPriceHistory();
    }
    hideDisabledFeatures();
}
Also used : BottomSheetDialog(com.google.android.material.bottomsheet.BottomSheetDialog) Chip(com.google.android.material.chip.Chip) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) Spanned(android.text.Spanned) TypeToken(com.google.gson.reflect.TypeToken) FragmentBottomsheetProductOverviewBinding(xyz.zedler.patrick.grocy.databinding.FragmentBottomsheetProductOverviewBinding) NonNull(androidx.annotation.NonNull) PriceHistoryEntry(xyz.zedler.patrick.grocy.model.PriceHistoryEntry) NumUtil(xyz.zedler.patrick.grocy.util.NumUtil) MainActivity(xyz.zedler.patrick.grocy.activity.MainActivity) Dialog(android.app.Dialog) HashMap(java.util.HashMap) TextUtil(xyz.zedler.patrick.grocy.util.TextUtil) MasterProductFragmentArgs(xyz.zedler.patrick.grocy.fragment.MasterProductFragmentArgs) ProductDetails(xyz.zedler.patrick.grocy.model.ProductDetails) DownloadHelper(xyz.zedler.patrick.grocy.helper.DownloadHelper) ArrayList(java.util.ArrayList) AmountUtil(xyz.zedler.patrick.grocy.util.AmountUtil) QuantityUnit(xyz.zedler.patrick.grocy.model.QuantityUnit) R(xyz.zedler.patrick.grocy.R) Gson(com.google.gson.Gson) View(android.view.View) Build(android.os.Build) StockItem(xyz.zedler.patrick.grocy.model.StockItem) MenuCompat(androidx.core.view.MenuCompat) NavHostFragment(androidx.navigation.fragment.NavHostFragment) PREF(xyz.zedler.patrick.grocy.util.Constants.PREF) PluralUtil(xyz.zedler.patrick.grocy.util.PluralUtil) BezierCurveChart(xyz.zedler.patrick.grocy.view.BezierCurveChart) LayoutInflater(android.view.LayoutInflater) Constants(xyz.zedler.patrick.grocy.util.Constants) Location(xyz.zedler.patrick.grocy.model.Location) ViewGroup(android.view.ViewGroup) Nullable(androidx.annotation.Nullable) SharedPreferences(android.content.SharedPreferences) Product(xyz.zedler.patrick.grocy.model.Product) Type(java.lang.reflect.Type) DateUtil(xyz.zedler.patrick.grocy.util.DateUtil) Html(android.text.Html) ViewTreeObserver(android.view.ViewTreeObserver) PreferenceManager(androidx.preference.PreferenceManager) ShoppingListItemEditFragmentArgs(xyz.zedler.patrick.grocy.fragment.ShoppingListItemEditFragmentArgs) Store(xyz.zedler.patrick.grocy.model.Store) Collections(java.util.Collections) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ValueAnimator(android.animation.ValueAnimator) PluralUtil(xyz.zedler.patrick.grocy.util.PluralUtil) MasterProductFragmentArgs(xyz.zedler.patrick.grocy.fragment.MasterProductFragmentArgs) StockItem(xyz.zedler.patrick.grocy.model.StockItem) DownloadHelper(xyz.zedler.patrick.grocy.helper.DownloadHelper) Chip(com.google.android.material.chip.Chip) Spanned(android.text.Spanned) LinearLayout(android.widget.LinearLayout)

Example 2 with MainActivity

use of xyz.zedler.patrick.grocy.activity.MainActivity in project grocy-android by patzly.

the class TasksFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    activity = (MainActivity) requireActivity();
    viewModel = new ViewModelProvider(this).get(TasksViewModel.class);
    viewModel.setOfflineLive(!activity.isOnline());
    binding.setViewModel(viewModel);
    binding.setActivity(activity);
    binding.setFragment(this);
    binding.setLifecycleOwner(getViewLifecycleOwner());
    infoFullscreenHelper = new InfoFullscreenHelper(binding.frame);
    clickUtil = new ClickUtil();
    // APP BAR BEHAVIOR
    appBarBehavior = new AppBarBehavior(activity, binding.appBarDefault, binding.appBarSearch, savedInstanceState);
    binding.recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
    binding.recycler.setAdapter(new MasterPlaceholderAdapter());
    if (savedInstanceState == null) {
        binding.recycler.scrollToPosition(0);
        viewModel.resetSearch();
    }
    viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), state -> {
        if (!state) {
            viewModel.setCurrentQueueLoading(null);
        }
    });
    viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
    viewModel.getFilteredTasksLive().observe(getViewLifecycleOwner(), items -> {
        if (items == null) {
            return;
        }
        if (items.isEmpty()) {
            InfoFullscreen info;
            if (viewModel.isSearchActive()) {
                info = new InfoFullscreen(InfoFullscreen.INFO_NO_SEARCH_RESULTS);
            } else {
                info = new InfoFullscreen(InfoFullscreen.INFO_EMPTY_TASKS);
            }
            viewModel.getInfoFullscreenLive().setValue(info);
        } else {
            viewModel.getInfoFullscreenLive().setValue(null);
        }
        if (binding.recycler.getAdapter() instanceof TasksItemAdapter) {
            ((TasksItemAdapter) binding.recycler.getAdapter()).updateData(items, viewModel.getSortMode());
        } else {
            binding.recycler.setAdapter(new TasksItemAdapter(requireContext(), items, this, viewModel.getSortMode()));
        }
    });
    viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
        if (event.getType() == Event.SNACKBAR_MESSAGE) {
            activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
        }
    });
    if (swipeBehavior == null) {
        swipeBehavior = new SwipeBehavior(activity, swipeStarted -> binding.swipe.setEnabled(!swipeStarted)) {

            @Override
            public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
                int position = viewHolder.getAdapterPosition();
                ArrayList<Task> displayedItems = viewModel.getFilteredTasksLive().getValue();
                if (displayedItems == null || position < 0 || position >= displayedItems.size()) {
                    return;
                }
                Task task = displayedItems.get(position);
                underlayButtons.add(new UnderlayButton(R.drawable.ic_round_done, pos -> {
                    if (pos >= displayedItems.size()) {
                        return;
                    }
                    swipeBehavior.recoverLatestSwipedItem();
                    viewModel.performAction(ACTION.UNDO, displayedItems.get(pos));
                }));
            }
        };
    }
    swipeBehavior.attachToRecyclerView(binding.recycler);
    hideDisabledFeatures();
    if (savedInstanceState == null) {
        viewModel.loadFromDatabase(true);
    }
    updateUI(savedInstanceState == null);
}
Also used : TasksItemAdapter(xyz.zedler.patrick.grocy.adapter.TasksItemAdapter) Bundle(android.os.Bundle) MasterPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.MasterPlaceholderAdapter) NonNull(androidx.annotation.NonNull) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) MainActivity(xyz.zedler.patrick.grocy.activity.MainActivity) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Event(xyz.zedler.patrick.grocy.model.Event) InfoFullscreen(xyz.zedler.patrick.grocy.model.InfoFullscreen) R(xyz.zedler.patrick.grocy.R) ActivityInfo(android.content.pm.ActivityInfo) ViewUtil(xyz.zedler.patrick.grocy.util.ViewUtil) View(android.view.View) Animation(android.view.animation.Animation) RecyclerView(androidx.recyclerview.widget.RecyclerView) ACTION(xyz.zedler.patrick.grocy.util.Constants.ACTION) ViewModelProvider(androidx.lifecycle.ViewModelProvider) LayoutInflater(android.view.LayoutInflater) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) Constants(xyz.zedler.patrick.grocy.util.Constants) POSITION(xyz.zedler.patrick.grocy.util.Constants.FAB.POSITION) ViewGroup(android.view.ViewGroup) FragmentTasksBinding(xyz.zedler.patrick.grocy.databinding.FragmentTasksBinding) Task(xyz.zedler.patrick.grocy.model.Task) List(java.util.List) Nullable(androidx.annotation.Nullable) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) TasksViewModel(xyz.zedler.patrick.grocy.viewmodel.TasksViewModel) SnackbarMessage(xyz.zedler.patrick.grocy.model.SnackbarMessage) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Snackbar(com.google.android.material.snackbar.Snackbar) Task(xyz.zedler.patrick.grocy.model.Task) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) MasterPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.MasterPlaceholderAdapter) ArrayList(java.util.ArrayList) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) TasksViewModel(xyz.zedler.patrick.grocy.viewmodel.TasksViewModel) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) InfoFullscreen(xyz.zedler.patrick.grocy.model.InfoFullscreen) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) TasksItemAdapter(xyz.zedler.patrick.grocy.adapter.TasksItemAdapter) RecyclerView(androidx.recyclerview.widget.RecyclerView) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 3 with MainActivity

use of xyz.zedler.patrick.grocy.activity.MainActivity in project grocy-android by patzly.

the class OnboardingFragment method onViewCreated.

@SuppressLint("ClickableViewAccessibility")
@Override
public void onViewCreated(@Nullable View view, @Nullable Bundle savedInstanceState) {
    activity = (MainActivity) requireActivity();
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
    binding.frameOnboardingPrevious.setOnClickListener(v -> {
        if (binding.pagerOnboarding.getCurrentItem() == 0) {
            return;
        }
        ViewUtil.startIcon(binding.imageOnboardingPrevious);
        binding.pagerOnboarding.setCurrentItem(binding.pagerOnboarding.getCurrentItem() - 1);
    });
    binding.frameOnboardingNext.setOnClickListener(v -> {
        if (binding.pagerOnboarding.getCurrentItem() == 3) {
            return;
        }
        ViewUtil.startIcon(binding.imageOnboardingNext);
        binding.pagerOnboarding.setCurrentItem(binding.pagerOnboarding.getCurrentItem() + 1);
    });
    setArrows(0, false);
    binding.buttonOnboardingStart.setOnClickListener(v -> {
        if (clickUtil.isDisabled()) {
            return;
        }
        activity.onBackPressed();
    });
    binding.pagerOnboarding.setAdapter(new OnboardingPagerAdapter(this));
    binding.pagerOnboarding.setCurrentItem(0);
    binding.pagerOnboarding.getChildAt(0).setOverScrollMode(View.OVER_SCROLL_NEVER);
    binding.pagerOnboarding.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

        @Override
        public void onPageSelected(int position) {
            setArrows(position, true);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            for (int i = 0; i < 3; i++) {
                if (fragments.containsKey(i) && fragments.get(i) != null) {
                    continue;
                }
                Fragment fragment = getChildFragmentManager().findFragmentByTag("f" + i);
                if (fragment == null) {
                    continue;
                }
                fragments.put(i, (OnboardingPageFragment) fragment);
                ((OnboardingPageFragment) fragment).updateLayout(false);
            }
            // active page
            setOffset(position, position, positionOffset);
            if (position != 0) {
                setOffset(position - 1, position, positionOffset);
            }
            if (position != binding.pagerOnboarding.getAdapter().getItemCount() - 1) {
                setOffset(position + 1, position, positionOffset);
            }
            binding.linearOnboardingTextLand.setAlpha(positionOffset < 0.5f ? 1 - 2 * positionOffset : 2 * positionOffset - 1);
            int positionNeeded = positionOffset < 0.5f ? position : position + 1;
            binding.textOnboardingTitleLand.setText(OnboardingPageFragment.getTitle(positionNeeded));
            binding.textOnboardingDescriptionLand.setText(OnboardingPageFragment.getDescription(positionNeeded));
        }
    });
    new TabLayoutMediator(binding.tabsOnboarding, binding.pagerOnboarding, (tab, position) -> {
    }).attach();
    LinearLayout tabStrip = (LinearLayout) binding.tabsOnboarding.getChildAt(0);
    for (int i = 0; i < tabStrip.getChildCount(); i++) {
        tabStrip.getChildAt(i).setOnTouchListener((v, event) -> true);
    }
}
Also used : ViewPager2(androidx.viewpager2.widget.ViewPager2) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) MainActivity(xyz.zedler.patrick.grocy.activity.MainActivity) ViewPager2(androidx.viewpager2.widget.ViewPager2) HashMap(java.util.HashMap) FragmentOnboardingPageBinding(xyz.zedler.patrick.grocy.databinding.FragmentOnboardingPageBinding) FragmentStateAdapter(androidx.viewpager2.adapter.FragmentStateAdapter) SuppressLint(android.annotation.SuppressLint) R(xyz.zedler.patrick.grocy.R) Fragment(androidx.fragment.app.Fragment) ViewUtil(xyz.zedler.patrick.grocy.util.ViewUtil) View(android.view.View) Animation(android.view.animation.Animation) FragmentOnboardingBinding(xyz.zedler.patrick.grocy.databinding.FragmentOnboardingBinding) LayoutInflater(android.view.LayoutInflater) Constants(xyz.zedler.patrick.grocy.util.Constants) ViewGroup(android.view.ViewGroup) Nullable(androidx.annotation.Nullable) SharedPreferences(android.content.SharedPreferences) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) Configuration(android.content.res.Configuration) ViewTreeObserver(android.view.ViewTreeObserver) PreferenceManager(androidx.preference.PreferenceManager) TabLayoutMediator(com.google.android.material.tabs.TabLayoutMediator) TabLayoutMediator(com.google.android.material.tabs.TabLayoutMediator) Fragment(androidx.fragment.app.Fragment) SuppressLint(android.annotation.SuppressLint) LinearLayout(android.widget.LinearLayout) SuppressLint(android.annotation.SuppressLint)

Example 4 with MainActivity

use of xyz.zedler.patrick.grocy.activity.MainActivity in project grocy-android by patzly.

the class ShoppingListFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    activity = (MainActivity) requireActivity();
    viewModel = new ViewModelProvider(this).get(ShoppingListViewModel.class);
    viewModel.setOfflineLive(!activity.isOnline());
    binding.setViewModel(viewModel);
    binding.setActivity(activity);
    binding.setFragment(this);
    binding.setLifecycleOwner(getViewLifecycleOwner());
    infoFullscreenHelper = new InfoFullscreenHelper(binding.frame);
    clickUtil = new ClickUtil();
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
    pluralUtil = new PluralUtil(activity);
    // APP BAR BEHAVIOR
    appBarBehavior = new AppBarBehavior(activity, binding.appBarDefault, binding.appBarSearch, savedInstanceState);
    binding.recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
    binding.recycler.setAdapter(new ShoppingPlaceholderAdapter());
    if (savedInstanceState == null) {
        binding.recycler.scrollToPosition(0);
        viewModel.resetSearch();
    }
    Object forcedSelectedId = getFromThisDestinationNow(Constants.ARGUMENT.SELECTED_ID);
    if (forcedSelectedId != null) {
        viewModel.selectShoppingList((Integer) forcedSelectedId);
        removeForThisDestination(Constants.ARGUMENT.SELECTED_ID);
    }
    viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), state -> {
        if (!state) {
            viewModel.setCurrentQueueLoading(null);
        }
    });
    viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
    viewModel.getSelectedShoppingListIdLive().observe(getViewLifecycleOwner(), this::changeAppBarTitle);
    viewModel.getFilteredShoppingListItemsLive().observe(getViewLifecycleOwner(), items -> {
        if (items == null)
            return;
        if (binding.recycler.getAdapter() instanceof ShoppingListItemAdapter) {
            ((ShoppingListItemAdapter) binding.recycler.getAdapter()).updateData(requireContext(), items, viewModel.getProductHashMap(), viewModel.getProductNamesHashMap(), viewModel.getQuantityUnitHashMap(), viewModel.getProductGroupHashMap(), viewModel.getStoreHashMap(), viewModel.getShoppingListItemAmountsHashMap(), viewModel.getMissingProductIds(), viewModel.getShoppingListNotes(), viewModel.getGroupingMode());
        } else {
            binding.recycler.setAdapter(new ShoppingListItemAdapter(requireContext(), items, viewModel.getProductHashMap(), viewModel.getProductNamesHashMap(), viewModel.getQuantityUnitHashMap(), viewModel.getProductGroupHashMap(), viewModel.getStoreHashMap(), viewModel.getShoppingListItemAmountsHashMap(), viewModel.getMissingProductIds(), this, viewModel.getShoppingListNotes(), viewModel.getGroupingMode()));
            binding.recycler.scheduleLayoutAnimation();
        }
    });
    viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
        if (event.getType() == Event.SNACKBAR_MESSAGE) {
            activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
        }
    });
    if (swipeBehavior == null) {
        swipeBehavior = new SwipeBehavior(activity, swipeStarted -> binding.swipeShoppingList.setEnabled(!swipeStarted)) {

            @Override
            public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
                if (viewHolder.getItemViewType() != GroupedListItem.TYPE_ENTRY)
                    return;
                if (!(binding.recycler.getAdapter() instanceof ShoppingListItemAdapter))
                    return;
                int position = viewHolder.getAdapterPosition();
                ArrayList<GroupedListItem> groupedListItems = ((ShoppingListItemAdapter) binding.recycler.getAdapter()).getGroupedListItems();
                if (groupedListItems == null || position < 0 || position >= groupedListItems.size()) {
                    return;
                }
                GroupedListItem item = groupedListItems.get(position);
                if (!(item instanceof ShoppingListItem)) {
                    return;
                }
                ShoppingListItem shoppingListItem = (ShoppingListItem) item;
                underlayButtons.add(new SwipeBehavior.UnderlayButton(R.drawable.ic_round_done, pos -> {
                    if (position >= groupedListItems.size()) {
                        return;
                    }
                    viewModel.toggleDoneStatus(shoppingListItem);
                }));
            }
        };
    }
    swipeBehavior.attachToRecyclerView(binding.recycler);
    hideDisabledFeatures();
    if (savedInstanceState == null) {
        viewModel.loadFromDatabase(true);
    }
    updateUI(ShoppingListFragmentArgs.fromBundle(requireArguments()).getAnimateStart() && savedInstanceState == null);
}
Also used : MutableLiveData(androidx.lifecycle.MutableLiveData) Bundle(android.os.Bundle) Spanned(android.text.Spanned) NonNull(androidx.annotation.NonNull) ShoppingListHelper(xyz.zedler.patrick.grocy.helper.ShoppingListHelper) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) GroupedListItem(xyz.zedler.patrick.grocy.model.GroupedListItem) NumUtil(xyz.zedler.patrick.grocy.util.NumUtil) MainActivity(xyz.zedler.patrick.grocy.activity.MainActivity) ShoppingListItemBottomSheet(xyz.zedler.patrick.grocy.fragment.bottomSheetDialog.ShoppingListItemBottomSheet) HashMap(java.util.HashMap) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Event(xyz.zedler.patrick.grocy.model.Event) ARGUMENT(xyz.zedler.patrick.grocy.util.Constants.ARGUMENT) QuantityUnit(xyz.zedler.patrick.grocy.model.QuantityUnit) R(xyz.zedler.patrick.grocy.R) ViewUtil(xyz.zedler.patrick.grocy.util.ViewUtil) View(android.view.View) SortUtil(xyz.zedler.patrick.grocy.util.SortUtil) RecyclerView(androidx.recyclerview.widget.RecyclerView) FragmentShoppingListBinding(xyz.zedler.patrick.grocy.databinding.FragmentShoppingListBinding) ShoppingListViewModel(xyz.zedler.patrick.grocy.viewmodel.ShoppingListViewModel) ViewModelProvider(androidx.lifecycle.ViewModelProvider) PluralUtil(xyz.zedler.patrick.grocy.util.PluralUtil) LayoutInflater(android.view.LayoutInflater) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) TextEditBottomSheet(xyz.zedler.patrick.grocy.fragment.bottomSheetDialog.TextEditBottomSheet) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) Constants(xyz.zedler.patrick.grocy.util.Constants) ShoppingList(xyz.zedler.patrick.grocy.model.ShoppingList) ViewGroup(android.view.ViewGroup) ShoppingListsBottomSheet(xyz.zedler.patrick.grocy.fragment.bottomSheetDialog.ShoppingListsBottomSheet) List(java.util.List) Nullable(androidx.annotation.Nullable) SharedPreferences(android.content.SharedPreferences) Product(xyz.zedler.patrick.grocy.model.Product) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) PreferenceManager(androidx.preference.PreferenceManager) ShoppingListItemAdapter(xyz.zedler.patrick.grocy.adapter.ShoppingListItemAdapter) ShoppingPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.ShoppingPlaceholderAdapter) ShoppingListClearBottomSheet(xyz.zedler.patrick.grocy.fragment.bottomSheetDialog.ShoppingListClearBottomSheet) ShoppingListItem(xyz.zedler.patrick.grocy.model.ShoppingListItem) SnackbarMessage(xyz.zedler.patrick.grocy.model.SnackbarMessage) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Snackbar(com.google.android.material.snackbar.Snackbar) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) GroupedListItem(xyz.zedler.patrick.grocy.model.GroupedListItem) PluralUtil(xyz.zedler.patrick.grocy.util.PluralUtil) ShoppingPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.ShoppingPlaceholderAdapter) ShoppingListItemAdapter(xyz.zedler.patrick.grocy.adapter.ShoppingListItemAdapter) ArrayList(java.util.ArrayList) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) ShoppingListItem(xyz.zedler.patrick.grocy.model.ShoppingListItem) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) ShoppingListViewModel(xyz.zedler.patrick.grocy.viewmodel.ShoppingListViewModel) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) RecyclerView(androidx.recyclerview.widget.RecyclerView) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Example 5 with MainActivity

use of xyz.zedler.patrick.grocy.activity.MainActivity in project grocy-android by patzly.

the class StockOverviewFragment method onViewCreated.

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    activity = (MainActivity) requireActivity();
    viewModel = new ViewModelProvider(this).get(StockOverviewViewModel.class);
    viewModel.setOfflineLive(!activity.isOnline());
    binding.setViewModel(viewModel);
    binding.setActivity(activity);
    binding.setFragment(this);
    binding.setLifecycleOwner(getViewLifecycleOwner());
    infoFullscreenHelper = new InfoFullscreenHelper(binding.frame);
    clickUtil = new ClickUtil();
    // APP BAR BEHAVIOR
    appBarBehavior = new AppBarBehavior(activity, binding.appBarDefault, binding.appBarSearch, savedInstanceState);
    binding.recycler.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
    binding.recycler.setAdapter(new StockPlaceholderAdapter());
    if (savedInstanceState == null) {
        binding.recycler.scrollToPosition(0);
        viewModel.resetSearch();
    }
    viewModel.getIsLoadingLive().observe(getViewLifecycleOwner(), state -> {
        if (!state) {
            viewModel.setCurrentQueueLoading(null);
        }
    });
    viewModel.getInfoFullscreenLive().observe(getViewLifecycleOwner(), infoFullscreen -> infoFullscreenHelper.setInfo(infoFullscreen));
    viewModel.getFilteredStockItemsLive().observe(getViewLifecycleOwner(), items -> {
        if (items == null)
            return;
        if (binding.recycler.getAdapter() instanceof StockOverviewItemAdapter) {
            ((StockOverviewItemAdapter) binding.recycler.getAdapter()).updateData(requireContext(), items, viewModel.getShoppingListItemsProductIds(), viewModel.getQuantityUnitHashMap(), viewModel.getProductGroupHashMap(), viewModel.getProductHashMap(), viewModel.getLocationHashMap(), viewModel.getProductIdsMissingStockItems(), viewModel.getSortMode(), viewModel.isSortAscending(), viewModel.getGroupingMode());
        } else {
            binding.recycler.setAdapter(new StockOverviewItemAdapter(requireContext(), items, viewModel.getShoppingListItemsProductIds(), viewModel.getQuantityUnitHashMap(), viewModel.getProductGroupHashMap(), viewModel.getProductHashMap(), viewModel.getLocationHashMap(), viewModel.getProductIdsMissingStockItems(), this, viewModel.isFeatureEnabled(PREF.FEATURE_STOCK_BBD_TRACKING), viewModel.isFeatureEnabled(PREF.FEATURE_SHOPPING_LIST), viewModel.getDaysExpriringSoon(), viewModel.getCurrency(), viewModel.getSortMode(), viewModel.isSortAscending(), viewModel.getGroupingMode()));
            binding.recycler.scheduleLayoutAnimation();
        }
    });
    embeddedFragmentScanner.setScannerVisibilityLive(viewModel.getScannerVisibilityLive());
    viewModel.getEventHandler().observeEvent(getViewLifecycleOwner(), event -> {
        if (event.getType() == Event.SNACKBAR_MESSAGE) {
            activity.showSnackbar(((SnackbarMessage) event).getSnackbar(activity, activity.binding.frameMainContainer));
        }
    });
    if (swipeBehavior == null) {
        swipeBehavior = new SwipeBehavior(activity, swipeStarted -> binding.swipe.setEnabled(!swipeStarted)) {

            @Override
            public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
                if (viewHolder.getItemViewType() != GroupedListItem.TYPE_ENTRY)
                    return;
                if (!(binding.recycler.getAdapter() instanceof StockOverviewItemAdapter))
                    return;
                int position = viewHolder.getAdapterPosition();
                ArrayList<GroupedListItem> groupedListItems = ((StockOverviewItemAdapter) binding.recycler.getAdapter()).getGroupedListItems();
                if (groupedListItems == null || position < 0 || position >= groupedListItems.size()) {
                    return;
                }
                GroupedListItem item = groupedListItems.get(position);
                if (!(item instanceof StockItem)) {
                    return;
                }
                StockItem stockItem = (StockItem) item;
                if (stockItem.getAmountAggregatedDouble() > 0 && stockItem.getProduct().getEnableTareWeightHandlingInt() == 0) {
                    underlayButtons.add(new SwipeBehavior.UnderlayButton(R.drawable.ic_round_consume_product, pos -> {
                        if (pos >= groupedListItems.size()) {
                            return;
                        }
                        swipeBehavior.recoverLatestSwipedItem();
                        viewModel.performAction(Constants.ACTION.CONSUME, stockItem);
                    }));
                }
                if (stockItem.getAmountAggregatedDouble() > stockItem.getAmountOpenedAggregatedDouble() && stockItem.getProduct().getEnableTareWeightHandlingInt() == 0 && viewModel.isFeatureEnabled(Constants.PREF.FEATURE_STOCK_OPENED_TRACKING)) {
                    underlayButtons.add(new SwipeBehavior.UnderlayButton(R.drawable.ic_round_open, pos -> {
                        if (pos >= groupedListItems.size()) {
                            return;
                        }
                        swipeBehavior.recoverLatestSwipedItem();
                        viewModel.performAction(Constants.ACTION.OPEN, stockItem);
                    }));
                }
                if (underlayButtons.isEmpty()) {
                    underlayButtons.add(new SwipeBehavior.UnderlayButton(R.drawable.ic_round_close, pos -> swipeBehavior.recoverLatestSwipedItem()));
                }
            }
        };
    }
    swipeBehavior.attachToRecyclerView(binding.recycler);
    hideDisabledFeatures();
    if (savedInstanceState == null) {
        viewModel.loadFromDatabase(true);
    }
    updateUI();
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) FragmentStockOverviewBinding(xyz.zedler.patrick.grocy.databinding.FragmentStockOverviewBinding) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) GroupedListItem(xyz.zedler.patrick.grocy.model.GroupedListItem) MainActivity(xyz.zedler.patrick.grocy.activity.MainActivity) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) Event(xyz.zedler.patrick.grocy.model.Event) QuantityUnit(xyz.zedler.patrick.grocy.model.QuantityUnit) R(xyz.zedler.patrick.grocy.R) ViewUtil(xyz.zedler.patrick.grocy.util.ViewUtil) View(android.view.View) Animation(android.view.animation.Animation) RecyclerView(androidx.recyclerview.widget.RecyclerView) StockItem(xyz.zedler.patrick.grocy.model.StockItem) BarcodeListener(xyz.zedler.patrick.grocy.scanner.EmbeddedFragmentScanner.BarcodeListener) EmbeddedFragmentScannerBundle(xyz.zedler.patrick.grocy.scanner.EmbeddedFragmentScannerBundle) ViewModelProvider(androidx.lifecycle.ViewModelProvider) PREF(xyz.zedler.patrick.grocy.util.Constants.PREF) LayoutInflater(android.view.LayoutInflater) StockPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.StockPlaceholderAdapter) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) StockOverviewItemAdapter(xyz.zedler.patrick.grocy.adapter.StockOverviewItemAdapter) Constants(xyz.zedler.patrick.grocy.util.Constants) Location(xyz.zedler.patrick.grocy.model.Location) ViewGroup(android.view.ViewGroup) EmbeddedFragmentScanner(xyz.zedler.patrick.grocy.scanner.EmbeddedFragmentScanner) List(java.util.List) Nullable(androidx.annotation.Nullable) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) SnackbarMessage(xyz.zedler.patrick.grocy.model.SnackbarMessage) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) StockOverviewViewModel(xyz.zedler.patrick.grocy.viewmodel.StockOverviewViewModel) AppBarBehavior(xyz.zedler.patrick.grocy.behavior.AppBarBehavior) GroupedListItem(xyz.zedler.patrick.grocy.model.GroupedListItem) ArrayList(java.util.ArrayList) SwipeBehavior(xyz.zedler.patrick.grocy.behavior.SwipeBehavior) StockItem(xyz.zedler.patrick.grocy.model.StockItem) InfoFullscreenHelper(xyz.zedler.patrick.grocy.helper.InfoFullscreenHelper) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) StockOverviewViewModel(xyz.zedler.patrick.grocy.viewmodel.StockOverviewViewModel) StockPlaceholderAdapter(xyz.zedler.patrick.grocy.adapter.StockPlaceholderAdapter) ClickUtil(xyz.zedler.patrick.grocy.util.ClickUtil) RecyclerView(androidx.recyclerview.widget.RecyclerView) StockOverviewItemAdapter(xyz.zedler.patrick.grocy.adapter.StockOverviewItemAdapter) ViewModelProvider(androidx.lifecycle.ViewModelProvider)

Aggregations

Bundle (android.os.Bundle)5 LayoutInflater (android.view.LayoutInflater)5 View (android.view.View)5 ViewGroup (android.view.ViewGroup)5 NonNull (androidx.annotation.NonNull)5 Nullable (androidx.annotation.Nullable)5 R (xyz.zedler.patrick.grocy.R)5 MainActivity (xyz.zedler.patrick.grocy.activity.MainActivity)5 Constants (xyz.zedler.patrick.grocy.util.Constants)5 ArrayList (java.util.ArrayList)4 SharedPreferences (android.content.SharedPreferences)3 MenuItem (android.view.MenuItem)3 Animation (android.view.animation.Animation)3 ViewModelProvider (androidx.lifecycle.ViewModelProvider)3 PreferenceManager (androidx.preference.PreferenceManager)3 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)3 RecyclerView (androidx.recyclerview.widget.RecyclerView)3 HashMap (java.util.HashMap)3 List (java.util.List)3 AppBarBehavior (xyz.zedler.patrick.grocy.behavior.AppBarBehavior)3