Search in sources :

Example 1 with PREVIEW_CARDS

use of com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS in project AnkiChinaAndroid by ankichinateam.

the class CardBrowser method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // FIXME:
    Timber.d("onActivityResult(requestCode=%d, resultCode=%d)", requestCode, resultCode);
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == DeckPicker.RESULT_DB_ERROR) {
        closeCardBrowser(DeckPicker.RESULT_DB_ERROR);
    }
    if (requestCode == EDIT_CARD && resultCode != RESULT_CANCELED) {
        Timber.i("CardBrowser:: CardBrowser: Saving card...");
        CollectionTask.launchCollectionTask(UPDATE_NOTE, updateCardHandler(), new TaskData(sCardBrowserCard, false));
    } else if (requestCode == ADD_NOTE && resultCode == RESULT_OK) {
        if (mSearchView != null) {
            mSearchTerms = mSearchView.getQuery().toString();
            searchCards();
        } else {
            Timber.w("Note was added from browser and on return mSearchView == null");
        }
    }
    // Previewing can now perform an "edit", so it can pass on a reloadRequired
    if (requestCode == PREVIEW_CARDS && data != null && (data.getBooleanExtra("reloadRequired", false) || data.getBooleanExtra("noteChanged", false))) {
        searchCards();
        if (getReviewerCardId() == mCurrentCardId) {
            mReloadRequired = true;
        }
    }
    if (requestCode == EDIT_CARD && data != null && (data.getBooleanExtra("reloadRequired", false) || data.getBooleanExtra("noteChanged", false))) {
        // if reloadRequired or noteChanged flag was sent from note editor then reload card list
        searchCards();
        // in use by reviewer?
        if (getReviewerCardId() == mCurrentCardId) {
            mReloadRequired = true;
        }
    }
    // maybe the availability of undo changed
    invalidateOptionsMenu();
}
Also used : TaskData(com.ichi2.async.TaskData)

Example 2 with PREVIEW_CARDS

use of com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS in project AnkiChinaAndroid by ankichinateam.

the class SelfStudyActivity method onActivityResult.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // FIXME:
    Timber.d("onActivityResult(requestCode=%d, resultCode=%d)", requestCode, resultCode);
    if (data != null) {
        Timber.d("onActivityResult data (reloadRequired=%s, noteChanged=%s)", data.getBooleanExtra("reloadRequired", false), data.getBooleanExtra("noteChanged", false));
    }
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == DeckPicker.RESULT_DB_ERROR) {
        closeCardBrowser(DeckPicker.RESULT_DB_ERROR);
    }
    if (requestCode == EDIT_CARD && resultCode != RESULT_CANCELED) {
        Timber.i("CardBrowser:: CardBrowser: Saving card...");
        CollectionTask.launchCollectionTask(UPDATE_NOTE, updateCardHandler(), new TaskData(sCardBrowserCard, false));
    } else if (requestCode == ADD_NOTE && resultCode == RESULT_OK) {
        if (mSearchView != null) {
            mSearchTerms = mSearchView.getQuery().toString();
            searchCards();
        } else {
            Timber.w("Note was added from browser and on return mSearchView == null");
        }
    }
    // }
    if (requestCode == PREVIEW_CARDS && data != null && (data.getBooleanExtra("reloadRequired", false) || data.getBooleanExtra("noteChanged", false))) {
        searchCards();
        if (getReviewerCardId() == mCurrentCardId) {
            mReloadRequired = true;
        }
    }
    if (requestCode == EDIT_CARD && data != null && (data.getBooleanExtra("reloadRequired", false) || data.getBooleanExtra("noteChanged", false))) {
        // if reloadRequired or noteChanged flag was sent from note editor then reload card list
        searchCards();
        // in use by reviewer?
        if (getReviewerCardId() == mCurrentCardId) {
            mReloadRequired = true;
        }
    }
    // maybe the availability of undo changed
    invalidateOptionsMenu();
}
Also used : TaskData(com.ichi2.async.TaskData)

Example 3 with PREVIEW_CARDS

use of com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS in project AnkiChinaAndroid by ankichinateam.

the class DeckInfoListAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(RecyclerView.ViewHolder tempHolder, int position) {
    if (tempHolder instanceof HeaderViewHolder) {
        HeaderViewHolder holder = (HeaderViewHolder) tempHolder;
        holder.mTextDeckName.setText(mTextDeckName);
        holder.mDeckListHeader.setVisibility(mDeckList.isEmpty() ? View.GONE : View.VISIBLE);
        // holder.mTextCongratsMessage.setText(mTextCongratsMessage);
        holder.mTextDeckDescription.setText(mTextDeckDescription != null && mTextDeckDescription.length() > 0 ? formatDescription(mTextDeckDescription) : "");
        holder.mTextTodayNew.setText(mTextTodayNew);
        holder.mTextTodayRev.setText(mTextTodayRev);
        holder.mTextCountHandled.setText(mTextCountHandled);
        holder.mTextCountLearning.setText(mTextCountLearning);
        holder.mTextCountNew.setText(mTextCountNew);
        holder.mTextCountHard.setText(mTextCountHard);
        holder.mTextTotal.setText(mTextTotal);
        holder.mTextHandledPercent.setText(mTextHandledPercent);
        holder.mTextHandledNum.setText(mTextHandledNum);
        holder.mTextETA.setText(mTextETA);
        holder.mButtonStart.setText(mTextButtonStart);
        holder.mButtonStart.setOnClickListener(mButtonStartClickListener);
        holder.mSelfStudyAskIcon.setOnClickListener(v -> {
            if (mSelfStudyQADialog == null) {
                mSelfStudyQADialog = new Dialog(mContext, R.style.CommonDialogTheme);
                View view = View.inflate(mContext, R.layout.pop_window_self_study_introduce, null);
                mSelfStudyQADialog.setContentView(view);
                Window window = mSelfStudyQADialog.getWindow();
                WindowManager.LayoutParams lps = window.getAttributes();
                lps.width = WindowManager.LayoutParams.MATCH_PARENT;
                window.setAttributes(lps);
                window.setGravity(Gravity.BOTTOM);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
            mSelfStudyQADialog.show();
        });
        holder.mStudyProgress.setProgress(mStudyProgress);
        // holder.mDeckInfoLayout.setVisibility(mDeckInfoLayoutVisible);
        // holder.mTextCongratsMessage.setVisibility(mTextCongratsMessageVisible);
        holder.mTextDeckDescription.setVisibility(mTextDeckDescriptionVisible);
        holder.mButtonStart.setEnabled(mButtonStartEnable);
        holder.mSelfStudyHandle.setTag(SelfStudyActivity.TAB_STUDY_STATE);
        holder.mSelfStudyMark.setTag(SelfStudyActivity.TAB_MARK_STATE);
        holder.mSelfStudyAnswer.setTag(SelfStudyActivity.TAB_ANSWER_STATE);
        holder.mSelfStudyCustom.setTag(SelfStudyActivity.TAB_CUSTOM_STATE);
        holder.mSelfStudyHandle.setOnClickListener(mSelfStudyClickListener);
        holder.mSelfStudyMark.setOnClickListener(mSelfStudyClickListener);
        holder.mSelfStudyAnswer.setOnClickListener(mSelfStudyClickListener);
        holder.mSelfStudyCustom.setOnClickListener(mSelfStudyClickListener);
        holder.mTextStudySetting.setVisibility(mCurrentDeck == null || mCurrentDeck.optInt("dyn", 0) == 1 ? View.GONE : View.VISIBLE);
        holder.mTextStudySetting.setOnClickListener(v -> {
            Intent i = new Intent(mContext, StudySettingActivity.class);
            i.putExtra("did", mCurrentDeck.optLong("id"));
            mContext.startActivityForResultWithAnimation(i, DECK_OPTIONS, ActivityTransitionAnimation.FADE);
        });
        if (AD_IMAGE_URL != null && !AD_IMAGE_URL.isEmpty() && AD_LINK_URL != null && !AD_LINK_URL.isEmpty()) {
            holder.mAdLayout.setVisibility(View.VISIBLE);
            CornerTransform transformation = new CornerTransform(mContext, AdaptionUtil.dip2px(mContext, 9));
            transformation.setExceptCorner(false, false, false, false);
            RequestOptions coverRequestOptions = new RequestOptions().transform(transformation).diskCacheStrategy(// 不做磁盘缓存
            DiskCacheStrategy.NONE).skipMemoryCache(// 不做内存缓存
            true);
            Glide.with(mContext).asBitmap().load(AD_IMAGE_URL).apply(coverRequestOptions).into(holder.mAdImage);
            holder.mAdLayout.setOnClickListener(v -> WebViewActivity.openUrlInApp(mContext, AD_LINK_URL, ""));
        } else {
            holder.mAdLayout.setVisibility(View.GONE);
        }
    } else if (tempHolder instanceof ViewHolder) {
        position--;
        ViewHolder holder = (ViewHolder) tempHolder;
        AbstractDeckTreeNode node = mDeckList.get(position);
        // Set the expander icon and padding according to whether or not there are any subdecks
        RelativeLayout deckLayout = holder.deckLayout;
        // int rightPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding);
        if (mHasSubdecks) {
            int smallPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_left_padding_small);
            deckLayout.setPadding(smallPadding, 0, (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding), 0);
            holder.deckExpander.setVisibility(View.VISIBLE);
            // Create the correct expander for this deck
            setDeckExpander(holder.deckExpander, holder.indentView, node);
        } else {
            holder.deckExpander.setVisibility(View.GONE);
            int normalPadding = (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_left_padding);
            deckLayout.setPadding(normalPadding, 0, (int) deckLayout.getResources().getDimension(R.dimen.deck_picker_right_padding), 0);
        }
        if (node.hasChildren()) {
            holder.deckExpander.setTag(node.getDid());
            holder.deckExpander.setOnClickListener(mDeckExpanderClickListener);
        } else {
            holder.deckExpander.setOnClickListener(null);
        }
        // holder.deckLayout.setBackgroundResource(mRowCurrentDrawable);
        // Set background colour. The current deck has its own color
        // if (isCurrentlySelectedDeck(node)) {
        // Timber.d("can be shown:%s", node.getDid());
        // Timber.d("mHasSubdecks:%s", node.hasChildren() + "");
        // if (mCurrentIDs.contains(node.getDid())) {
        // holder.deckLayout.setVisibility(View.VISIBLE);
        // holder.deckLayout.setBackgroundResource(mRowCurrentDrawable);
        // if (mPartiallyTransparentForBackground) {
        // setBackgroundAlpha(holder.deckLayout, SELECTED_DECK_ALPHA_AGAINST_BACKGROUND);
        // }
        // } else {
        // holder.deckLayout.setVisibility(View.GONE);
        // CompatHelper.getCompat().setSelectableBackground(holder.deckLayout);
        // }
        // Set deck name and colour. Filtered decks have their own colour
        holder.deckName.setText(node.getLastDeckNameComponent());
        if (mCol.getDecks().isDyn(node.getDid())) {
            holder.deckName.setTextColor(mDeckNameDynColor);
        } else {
            if (node.getDepth() == Decks.path(mCurrentDeck.optString("name")).length) {
                holder.deckName.setTextColor(mDeckNameDefaultColor);
            } else {
                holder.deckName.setTextColor(mDeckNameDefaultColorChild);
            }
        }
        if (node.shouldDisplayCounts()) {
            // holder.deckNew.setText(String.valueOf(node.getNewCount()));
            // holder.deckLearn.setText(String.valueOf(node.getLrnCount()));
            // holder.deckRev.setText(String.valueOf(node.getRevCount()+node.getLrnCount()));
            holder.deckNew.setText(String.valueOf(node.getNewCount() + node.getRevCount() + node.getLrnCount()));
            String ids = Stats.deckLimit(node.getDid(), mCol);
            holder.deckRev.setText(String.valueOf(mCol.cardCount(ids)));
        }
        // Store deck ID in layout's tag for easy retrieval in our click listeners
        holder.deckLayout.setTag(node.getDid());
        holder.countsLayout.setTag(node.getDid());
        holder.endIcon.setTag(node.getDid());
        // holder.endLayout.setTag(node.getDid());
        // Set click listeners
        holder.deckLayout.setOnClickListener(mDeckClickListener);
        holder.deckLayout.setOnLongClickListener(mDeckLongClickListener);
        holder.countsLayout.setOnClickListener(mCountsClickListener);
        holder.endIcon.setOnClickListener(mCountsClickListener);
    // holder.endLayout.setOnClickListener(mCountsClickListener);
    } else if (mCurrentDeck != null) {
        if (tempHolder instanceof CardsListAdapter.CardsViewHolder) {
            CardsListAdapter.CardsViewHolder holder = (CardsListAdapter.CardsViewHolder) tempHolder;
            CardBrowser.CardCache card = mCards.get(position - mDeckList.size() - 1 - 1);
            Timber.i("refresh card:%s", card.getId());
            String question = card.getColumnHeaderText(CardBrowser.Column.SFLD);
            if (card.getColumnHeaderText(CardBrowser.Column.SUSPENDED).equals("True")) {
                holder.deckQuestion.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
            // holder.deckAnswer.setTextColor(ContextCompat.getColor(mContext, R.color.new_primary_text_third_color));
            }
            String firstColumnStr = question.isEmpty() ? card.getColumnHeaderText(CardBrowser.Column.MEDIA_NAME) : card.getColumnHeaderText(CardBrowser.Column.SFLD);
            Pattern pattern = Pattern.compile("(?<=≯#).*?(?=#≮)");
            Matcher matcher = pattern.matcher(firstColumnStr);
            String val = "";
            if (matcher.find()) {
                val = matcher.group(0);
                try {
                    String key = mModelKeys.getString(String.valueOf(card.getCard().model().getLong("id")));
                    Timber.i("match key:%s", key);
                    holder.deckQuestion.setText(HtmlUtils.delHTMLTag(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + AESUtil.decrypt(val, key) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2)));
                // holder.deckQuestion.setText(firstColumnStr.substring(0, firstColumnStr.indexOf("≯#")) + aesUtil.getDecryptedMessage(val) + firstColumnStr.substring(firstColumnStr.indexOf("#≮") + 2));
                } catch (Exception e) {
                    e.printStackTrace();
                    holder.deckQuestion.setText(firstColumnStr);
                }
            } else {
                holder.deckQuestion.setText(firstColumnStr);
            }
            // holder.deckAnswer.setText(card.getColumnHeaderText(CardBrowser.Column.ANSWER));
            holder.reviewCount.setText(card.getColumnHeaderText(CardBrowser.Column.REVIEWS));
            holder.forgetCount.setText(card.getColumnHeaderText(CardBrowser.Column.LAPSES));
            holder.due.setText(card.getColumnHeaderText(CardBrowser.Column.DUE2));
            holder.mark.setTag(card.getId());
            holder.flag.setTag(card.getId());
            holder.itemRoot.setTag(card.getId());
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) holder.itemRoot.getLayoutParams();
            layoutParams.rightMargin = 0;
            holder.itemRoot.setLayoutParams(layoutParams);
            if (card.getCard().note().hasTag("marked")) {
                holder.mark.setImageResource(R.mipmap.mark_star_normal);
            } else {
                holder.mark.setImageResource(R.mipmap.note_star_unselected);
            }
            if (getFlagRes(card.getCard()) != -1) {
                holder.flag.setImageResource(getFlagRes(card.getCard()));
            } else {
                holder.flag.setImageResource(R.mipmap.note_flag_unselected);
            }
            holder.mark.setOnClickListener(v -> {
                CollectionTask.launchCollectionTask(DISMISS_MULTI, markCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.MARK_NOTE_MULTI }));
                notifyDataSetChanged();
            });
            holder.flag.setOnClickListener(v -> {
                if (mListPop == null) {
                    mListPop = new ListPopupWindow(mContext);
                    for (int i = 0; i < mFlagRes.length; i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("img", mFlagRes[i]);
                        map.put("content", mFlagContent[i]);
                        mFlagList.add(map);
                    }
                    mListPop.setAdapter(new SimpleAdapter(mContext, mFlagList, R.layout.item_flags_list, new String[] { "img", "content" }, new int[] { R.id.flag_icon, R.id.flag_text }));
                    mListPop.setWidth(v.getRootView().getWidth() / 2);
                    mListPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                    // 设置是否是模式
                    mListPop.setModal(true);
                }
                mListPop.setOnItemClickListener((parent, view, position1, id) -> {
                    CollectionTask.launchCollectionTask(DISMISS_MULTI, flagCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.FLAG, position1 }));
                    notifyDataSetChanged();
                    mListPop.dismiss();
                });
                mListPop.setAnchorView(v);
                mListPop.show();
            });
            holder.itemRoot.setOnClickListener(v -> {
                Intent previewer = new Intent(mContext, Previewer.class);
                long[] ids = getAllCardIds();
                long targetId = (long) v.getTag();
                // }
                for (int i = 0; i < ids.length; i++) {
                    if (ids[i] == targetId) {
                        previewer.putExtra("index", i);
                        break;
                    }
                }
                previewer.putExtra("cardList", ids);
                mContext.startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
            });
        // holder.itemRoot.setOnLongClickListener(mDeckLongClickListener);
        } else if (tempHolder instanceof BrowserTabViewHolder) {
            BrowserTabViewHolder holder = (BrowserTabViewHolder) tempHolder;
            String[] tabArray = mContext.getResources().getStringArray(R.array.deck_info_browser_tab);
            holder.cardsCount.setText(String.format("筛选出%d张卡片", mCards.size()));
            // CardsListAdapter  mCardsAdapter = new CardsListAdapter(mContext.getLayoutInflater(), mContext, new CardsListAdapter.CardListAdapterCallback() {
            // @Override
            // public List<CardBrowser.CardCache> getCards() {
            // if (mCards == null) {
            // mCards = new ArrayList<>();
            // }
            // return mCards;
            // }
            // 
            // 
            // @Override
            // public void onChangeMultiMode(boolean isMultiMode) {
            // }
            // 
            // 
            // @Override
            // public void onItemSelect(int count) {
            // }
            // });
            // mCardsAdapter.setStudyCountLayoutRes(R.layout.item_option_study_count);
            // mCardsAdapter.setDeckClickListener(view -> {
            // Intent previewer = new Intent(mContext, Previewer.class);
            // long[] ids =  getAllCardIds();
            // long targetId = (long) view.getTag();
            // if (ids.length > 100) {
            // //为提高效率 直接复制卡牌
            // long[] finalIds = new long[ids.length + 1];
            // finalIds[0] = targetId;
            // System.arraycopy(ids, 0, finalIds, 1, ids.length);
            // previewer.putExtra("cardList", finalIds);
            // } else {
            // for (int i = 0; i < ids.length; i++) {
            // if (ids[i] == targetId) {
            // ids[i] = ids[0];
            // ids[0] = targetId;
            // }
            // }
            // previewer.putExtra("cardList", ids);
            // }
            // previewer.putExtra("index", 0);
            // mContext.startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
            // });
            // holder.mList .setAdapter(mCardsAdapter);
            // holder.mList.setRecycledViewPool(new RecyclerView.RecycledViewPool());
            // holder.mList.setNestedScrollingEnabled(false);
            // holder.mList.setHasFixedSize(true);
            // holder.mList.setLayoutManager(new LinearLayoutManager(mContext));
            holder.mMore.setTag(SelfStudyActivity.TAB_MAIN_STATE);
            holder.mFixBottom.setVisibility(mDeckList.isEmpty() ? View.GONE : View.VISIBLE);
            holder.mMore.setOnClickListener(mSelfStudyClickListener);
            holder.mTabLayout.removeAllTabs();
            LinearLayout linearLayout = (LinearLayout) holder.mTabLayout.getChildAt(0);
            linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
            linearLayout.setDividerDrawable(ContextCompat.getDrawable(mContext, // 设置分割线的样式
            R.drawable.divider_vertical));
            // 设置分割线间隔
            linearLayout.setDividerPadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, mContext.getResources().getDisplayMetrics()));
            for (int i = 0; i < tabArray.length; i++) {
                TabLayout.Tab tab = holder.mTabLayout.newTab();
                View view = mContext.getLayoutInflater().inflate(R.layout.item_option_tab, null);
                ((TextView) view.findViewById(R.id.name)).setText(tabArray[i]);
                tab.setCustomView(view);
                view.setTag(i);
                int finalI = i;
                view.setOnClickListener(v -> {
                    if (mContext.colIsOpen()) {
                        mCurrentSelectedTab = finalI;
                        holder.mTabLayout.selectTab(holder.mTabLayout.getTabAt(finalI));
                        // estimate maximum number of cards that could be visible (assuming worst-case minimum row height of 20dp)
                        int numCardsToRender = (int) Math.ceil(holder.mList.getHeight() / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, mContext.getResources().getDisplayMetrics())) + 5;
                        Timber.i("I wanna get %d cards", numCardsToRender);
                        // Perform database query to get all card ids
                        mSearchCardsHandler = new SearchCardsHandler();
                        String searchText = getRestrictByTab(finalI) + "deck:\"" + mCurrentDeck.getString("name") + "\" ";
                        CollectionTask.launchCollectionTask(SEARCH_CARDS, mSearchCardsHandler, new TaskData(new Object[] { searchText, true, numCardsToRender, 0, 0 }));
                    }
                });
                holder.mTabLayout.addTab(tab);
            }
            holder.mTabLayout.selectTab(holder.mTabLayout.getTabAt(mCurrentSelectedTab));
            if (!mInitBrowserCards) {
                mInitBrowserCards = true;
                holder.mTabLayout.getTabAt(0).getCustomView().performClick();
            }
        }
    }
}
Also used : ImageButton(android.widget.ImageButton) LinearLayout(android.widget.LinearLayout) Arrays(java.util.Arrays) Deck(com.ichi2.libanki.Deck) ProgressBar(android.widget.ProgressBar) NonNull(androidx.annotation.NonNull) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) LinkMovementMethod(android.text.method.LinkMovementMethod) Drawable(android.graphics.drawable.Drawable) SelfStudyActivity(com.ichi2.anki.SelfStudyActivity) Decks(com.ichi2.libanki.Decks) Matcher(java.util.regex.Matcher) Map(java.util.Map) Previewer(com.ichi2.anki.Previewer) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) RecyclerView(androidx.recyclerview.widget.RecyclerView) StudySettingActivity(com.ichi2.anki.StudySettingActivity) ContextCompat(androidx.core.content.ContextCompat) CardView(androidx.cardview.widget.CardView) DeckPicker(com.ichi2.anki.DeckPicker) HtmlUtils(com.ichi2.utils.HtmlUtils) TabLayout(com.google.android.material.tabs.TabLayout) CardUtils(com.ichi2.anki.CardUtils) SEARCH_CARDS(com.ichi2.async.CollectionTask.TASK_TYPE.SEARCH_CARDS) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) CardBrowser(com.ichi2.anki.CardBrowser) Timber(timber.log.Timber) ViewGroup(android.view.ViewGroup) CollectionHelper(com.ichi2.anki.CollectionHelper) AnkiActivity(com.ichi2.anki.AnkiActivity) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) SimpleAdapter(android.widget.SimpleAdapter) AnkiDroidApp(com.ichi2.anki.AnkiDroidApp) Consts(com.ichi2.libanki.Consts) CompatHelper(com.ichi2.compat.CompatHelper) RelativeLayout(android.widget.RelativeLayout) DECK_OPTIONS(com.ichi2.anki.AbstractFlashcardViewer.DECK_OPTIONS) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Pattern(java.util.regex.Pattern) Window(android.view.Window) WebViewActivity(com.ichi2.anki.WebViewActivity) TaskListener(com.ichi2.async.TaskListener) Spanned(android.text.Spanned) CornerTransform(com.ichi2.utils.CornerTransform) R(com.ichi2.anki.R) Dialog(android.app.Dialog) Intent(android.content.Intent) HashMap(java.util.HashMap) DISMISS_MULTI(com.ichi2.async.CollectionTask.TASK_TYPE.DISMISS_MULTI) Collection(com.ichi2.libanki.Collection) TypedArray(android.content.res.TypedArray) ArrayList(java.util.ArrayList) CardsListAdapter.getFlagRes(com.ichi2.anki.widgets.CardsListAdapter.getFlagRes) DiskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy) Utils(com.ichi2.libanki.Utils) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) RequestOptions(com.bumptech.glide.request.RequestOptions) AbstractDeckTreeNode(com.ichi2.libanki.sched.AbstractDeckTreeNode) Stats(com.ichi2.libanki.stats.Stats) LayoutInflater(android.view.LayoutInflater) CollectionTask(com.ichi2.async.CollectionTask) SelfStudyActivity.getPositionMap(com.ichi2.anki.SelfStudyActivity.getPositionMap) Color(android.graphics.Color) Gravity(android.view.Gravity) AESUtil(com.ichi2.utils.AESUtil) Glide(com.bumptech.glide.Glide) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) TreeMap(java.util.TreeMap) AdaptionUtil(com.ichi2.utils.AdaptionUtil) PREVIEW_CARDS(com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS) Card(com.ichi2.libanki.Card) KEY_STRUCT_INIT(com.ichi2.anki.StudyOptionsFragment.KEY_STRUCT_INIT) VisibleForTesting(androidx.annotation.VisibleForTesting) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) RequestOptions(com.bumptech.glide.request.RequestOptions) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) CardBrowser(com.ichi2.anki.CardBrowser) WindowManager(android.view.WindowManager) TaskData(com.ichi2.async.TaskData) CornerTransform(com.ichi2.utils.CornerTransform) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) Dialog(android.app.Dialog) AbstractDeckTreeNode(com.ichi2.libanki.sched.AbstractDeckTreeNode) Window(android.view.Window) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) Pattern(java.util.regex.Pattern) SimpleAdapter(android.widget.SimpleAdapter) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) CardView(androidx.cardview.widget.CardView) TextView(android.widget.TextView) ColorDrawable(android.graphics.drawable.ColorDrawable) RelativeLayout(android.widget.RelativeLayout) JSONObject(com.ichi2.utils.JSONObject) LinearLayout(android.widget.LinearLayout)

Example 4 with PREVIEW_CARDS

use of com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS in project AnkiChinaAndroid by ankichinateam.

the class SelfStudyActivity method onCollectionLoaded.

// Finish initializing the activity after the collection has been correctly loaded
@Override
protected void onCollectionLoaded(Collection col) {
    super.onCollectionLoaded(col);
    Timber.d("onCollectionLoaded()");
    registerExternalStorageListener();
    final SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
    // Load reference to action bar title
    mActionBarTitle = findViewById(R.id.toolbar_title);
    mTabLayout = findViewById(R.id.tab_layout);
    mTop = findViewById(R.id.invisible_top);
    mTop.setVisibility(View.GONE);
    mRestrictOnTab = "";
    mTabType = getIntent().getIntExtra("type", 0);
    mComplete = findViewById(R.id.tv_complete);
    mComplete.setOnClickListener(v -> toggleMultiSelectMode(false));
    mBack = findViewById(R.id.iv_back);
    mStartStudyButton = findViewById(R.id.confirm);
    mStartStudyButton.setOnClickListener(v -> {
        boolean showDialog = false;
        try {
            if (!preferences.getString(Consts.KEY_SELF_STUDYING_LIST, "").isEmpty()) {
                String[] savedCardListStr = preferences.getString(Consts.KEY_SELF_STUDYING_LIST, "").replace("[", "").replace("]", "").split(", ");
                long[] savedCardList = new long[savedCardListStr.length];
                for (int i = 0; i < savedCardListStr.length; i++) {
                    savedCardList[i] = Long.parseLong(savedCardListStr[i]);
                }
                List<Long> newCardList = getCol().filterToValidCards(savedCardList);
                long[] filterToValidCards = new long[newCardList.size()];
                for (int i = 0; i < newCardList.size(); i++) {
                    filterToValidCards[i] = newCardList.get(i);
                }
                if (preferences.getInt(Consts.KEY_SELF_STUDYING_LIST_INDEX, 0) + 1 < savedCardListStr.length) {
                    // 没跑完
                    Intent previewer = new Intent(SelfStudyActivity.this, Previewer2.class);
                    CustomStyleDialog studyDialog = new CustomStyleDialog.Builder(this).setCustomLayout(R.layout.dialog_common_custom_next).setTitle("是否继续上一次的主动练习?").centerTitle().setMessage("你上次的主动练习还有待学任务,请选择是继续上一次还是开始新的主动练习").setPositiveButton("开始新的", (dialog, which) -> {
                        dialog.dismiss();
                        long[] cardList;
                        if (inMultiSelectMode() && checkedCardCount() > 1) {
                            // Multiple cards have been explicitly selected, so preview only those cards
                            previewer.putExtra("index", 0);
                            cardList = getSelectedCardIds();
                        } else {
                            // Preview all cards, starting from the one that is currently selected
                            // int startIndex = mCheckedCards.isEmpty() ? 0 : mCheckedCards.iterator().next().getPosition();
                            previewer.putExtra("index", 0);
                            cardList = getAllCardIds();
                        }
                        previewer.putExtra("cardList", cardList);
                        preferences.edit().putString(Consts.KEY_SELF_STUDYING_LIST, Arrays.toString(cardList)).putInt(Consts.KEY_SELF_STUDYING_LIST_INDEX, 0).apply();
                        startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
                    }).setNegativeButton("继续上次", (dialog, which) -> {
                        dialog.dismiss();
                        previewer.putExtra("cardList", filterToValidCards);
                        previewer.putExtra("index", preferences.getInt(Consts.KEY_SELF_STUDYING_LIST_INDEX, 0));
                        startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
                    }).create();
                    showDialog = true;
                    studyDialog.show();
                }
            }
        } catch (Exception ignored) {
        }
        if (!showDialog) {
            Intent previewer = new Intent(SelfStudyActivity.this, Previewer2.class);
            long[] cardList;
            if (inMultiSelectMode() && checkedCardCount() > 1) {
                // Multiple cards have been explicitly selected, so preview only those cards
                previewer.putExtra("index", 0);
                cardList = getSelectedCardIds();
            } else {
                // Preview all cards, starting from the one that is currently selected
                // int startIndex = mCheckedCards.isEmpty() ? 0 : mCheckedCards.iterator().next().getPosition();
                previewer.putExtra("index", 0);
                cardList = getAllCardIds();
            }
            previewer.putExtra("cardList", cardList);
            preferences.edit().putString(Consts.KEY_SELF_STUDYING_LIST, Arrays.toString(cardList)).putInt(Consts.KEY_SELF_STUDYING_LIST_INDEX, 0).apply();
            startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
        }
    });
    // Add drop-down menu to select deck to action bar.
    mDropDownDecks = getCol().getDecks().allSorted();
    mDropDownDeckAdapter = new DeckDropDownAdapter(this, mDropDownDecks, R.layout.dropdown_deck_selected_item_self, this);
    mToolbar = findViewById(R.id.toolbar);
    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
    // enable ActionBar app icon to behave as action to toggle nav drawer
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // getSupportActionBar().setHomeButtonEnabled(true);
    // Decide which action to take when the navigation button is tapped.
    // mToolbar.setNavigationIcon(R.mipmap.nav_bar_back_normal);
    // mToolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    ActionBar mActionBar = getSupportActionBar();
    if (mActionBar != null) {
        mActionBar.setDisplayShowTitleEnabled(false);
    }
    // mOrder = CARD_ORDER_CREATE_TIME;
    String colOrder = getCol().getConf().getString("sortType");
    for (int c = 0; c < fSortTypes.length; ++c) {
        if (fSortTypes[c].equals(colOrder)) {
            mOrder = c;
            break;
        }
    }
    if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
        mOrder = 0;
    }
    // This upgrade should already have been done during
    // setConf. However older version of AnkiDroid didn't call
    // upgradeJSONIfNecessary during setConf, which means the
    // conf saved may still have this bug.
    mOrderAsc = Upgrade.upgradeJSONIfNecessary(getCol(), getCol().getConf(), "sortBackwards", false);
    // mOrderAsc = true;
    getCol().getConf().put("sortType", fSortTypes[mOrder]);
    getCol().getConf().put("sortBackwards", mOrderAsc);
    mCards = new ArrayList<>();
    mCardsListView = findViewById(R.id.card_browser_list);
    mMultiModeBottomLayout = findViewById(R.id.rl_multi_mode);
    findViewById(R.id.add_note_action).setOnClickListener(v -> {
        Intent intent = new Intent(SelfStudyActivity.this, NoteEditor.class);
        intent.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_CARDBROWSER_ADD);
        startActivityForResultWithAnimation(intent, ADD_NOTE, ActivityTransitionAnimation.LEFT);
    });
    TextView selectCount = findViewById(R.id.select_count);
    TextView move = findViewById(R.id.move);
    TextView delete = findViewById(R.id.delete);
    TextView cancel = findViewById(R.id.cancel);
    CheckBox stick = findViewById(R.id.stick);
    move.setOnClickListener(v -> {
        if (mCardsAdapter.getSelectedItemIds().isEmpty()) {
            return;
        }
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(SelfStudyActivity.this);
        builderSingle.setTitle(getString(R.string.move_all_to_deck));
        // WARNING: changeDeck depends on this index, so any changes should be reflected there.
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SelfStudyActivity.this, R.layout.dropdown_deck_item);
        for (Deck deck : getValidDecksForChangeDeck()) {
            try {
                arrayAdapter.add(deck.getString("name"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        builderSingle.setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
        builderSingle.setAdapter(arrayAdapter, (dialog, which) -> changeDeck(which));
        builderSingle.show();
    });
    delete.setOnClickListener(v -> {
        if (mCardsAdapter.getSelectedItemIds().isEmpty()) {
            return;
        }
        CollectionTask.launchCollectionTask(DISMISS_MULTI, mDeleteNoteHandler, new TaskData(new Object[] { mCardsAdapter.getSelectedItemIdArray(), Collection.DismissType.DELETE_NOTE_MULTI }));
        toggleMultiSelectMode(false);
        mCardsAdapter.getSelectedItemIds().clear();
        mCardsAdapter.notifyDataSetChanged();
    });
    int[] attrs = new int[] { R.attr.primary_text_third_color999999 };
    TypedArray ta = obtainStyledAttributes(attrs);
    int textGrayColor = ta.getColor(0, ContextCompat.getColor(this, R.color.new_primary_text_third_color));
    ta.recycle();
    stick.setOnCheckedChangeListener((buttonView, isChecked) -> {
        mCardsAdapter.selectItem(isChecked);
        selectCount.setText((isChecked ? "全选" : "已选") + mCardsAdapter.selectItemCount());
        selectCount.setTextColor(isChecked ? ContextCompat.getColor(this, R.color.primary_color) : textGrayColor);
    });
    selectCount.setOnClickListener(v -> stick.performClick());
    cancel.setOnClickListener(v -> {
        toggleMultiSelectMode(false);
    });
    mCardsAdapter = new CardsListAdapter(getLayoutInflater(), this, new CardsListAdapter.CardListAdapterCallback() {

        @Override
        public List<CardCache> getCards() {
            return SelfStudyActivity.this.getCards();
        }

        @Override
        public void onChangeMultiMode(boolean isMultiMode) {
            mMultiModeBottomLayout.setVisibility(isMultiMode ? View.VISIBLE : View.GONE);
            mStartStudyButton.setVisibility(isMultiMode ? View.GONE : mCards.size() > 0 ? View.VISIBLE : View.GONE);
            mSearchView.setVisibility(isMultiMode ? View.INVISIBLE : View.VISIBLE);
            mBack.setVisibility(isMultiMode ? View.GONE : View.VISIBLE);
            mComplete.setVisibility(isMultiMode ? View.VISIBLE : View.GONE);
            selectCount.setText("已选0");
            supportInvalidateOptionsMenu();
        }

        @Override
        public void onItemSelect(int count) {
            selectCount.setText("已选" + count);
            updateMultiselectMenu();
        }
    });
    // link the adapter to the main mCardsListView
    mCardsListView.setAdapter(mCardsAdapter);
    mCardsListView.setLayoutManager(new LinearLayoutManager(this));
    mCardsAdapter.setTvOrderClickListener(v -> showOrderListDialog());
    mCardsAdapter.setIvOrderClickListener(v -> {
        // 修改升序/降序
        mOrderAsc = !mOrderAsc;
        getCol().getConf().put("sortBackwards", mOrderAsc);
        Collections.reverse(mCards);
        updateList();
        mCardsAdapter.updateOrderState(mOrderNames[mOrder], mOrderAsc);
    });
    mCardsAdapter.setDeckClickListener(view -> {
        if (mCardsAdapter.isMultiCheckableMode()) {
            return;
        }
        Intent previewer = new Intent(SelfStudyActivity.this, Previewer.class);
        long[] ids = inMultiSelectMode() && checkedCardCount() > 1 ? getSelectedCardIds() : getAllCardIds();
        long targetId = (long) view.getTag();
        for (int i = 0; i < ids.length; i++) {
            if (ids[i] == targetId) {
                previewer.putExtra("index", i);
                break;
            }
        }
        previewer.putExtra("cardList", ids);
        startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
    // openNoteEditorForCard((long) view.getTag());
    });
    mCardsAdapter.setDeckLongClickListener(view -> {
        if (mCardsAdapter.isMultiCheckableMode()) {
            return false;
        }
        mCardsAdapter.setMultiCheckable(true);
        return true;
    });
    mCardsAdapter.setMarkClickListener(v -> {
        CollectionTask.launchCollectionTask(DISMISS_MULTI, markCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.MARK_NOTE_MULTI }));
        mCardsAdapter.notifyDataSetChanged();
    });
    mOrderNames = getResources().getStringArray(R.array.card_browser_order_labels);
    mCardsAdapter.updateOrderState(mOrderNames[mOrder], mOrderAsc);
    mCardsAdapter.setFlagClickListener(v -> {
        if (mListPop == null) {
            mListPop = new ListPopupWindow(this);
            for (int i = 0; i < mFlagRes.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("img", mFlagRes[i]);
                map.put("content", mFlagContent[i]);
                mFlagList.add(map);
            }
            mListPop.setAdapter(new SimpleAdapter(SelfStudyActivity.this, mFlagList, R.layout.item_flags_list, new String[] { "img", "content" }, new int[] { R.id.flag_icon, R.id.flag_text }));
            mListPop.setWidth(v.getRootView().getWidth() / 2);
            mListPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置是否是模式
            mListPop.setModal(true);
        }
        mListPop.setOnItemClickListener((parent, view, position, id) -> {
            CollectionTask.launchCollectionTask(DISMISS_MULTI, flagCardHandler(), new TaskData(new Object[] { new long[] { (long) v.getTag() }, Collection.DismissType.FLAG, position }));
            mCardsAdapter.notifyDataSetChanged();
            mListPop.dismiss();
        });
        mListPop.setAnchorView(v);
        mListPop.show();
    });
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    // If a valid value for last deck exists then use it, otherwise use libanki selected deck
    if ((getLastDeckId() != null && getLastDeckId() == ALL_DECKS_ID)) {
        selectAllDecks();
    } else if (getLastDeckId() != null && getCol().getDecks().get(getLastDeckId(), false) != null) {
        selectDeckById(getLastDeckId());
    } else {
        selectDeckById(getCol().getDecks().selected());
    }
    initSearchView();
    initTabLayout();
    findViewById(R.id.shadeView).setOnClickListener(v -> {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        if (mOrderListWindow != null && mOrderListWindow.isShowing()) {
            mOrderListWindow.dismiss();
        }
    });
}
Also used : Arrays(java.util.Arrays) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) ImageView(android.widget.ImageView) RangeSeekBar(com.jaygoo.widget.RangeSeekBar) ActionBar(androidx.appcompat.app.ActionBar) Decks(com.ichi2.libanki.Decks) Handler(android.os.Handler) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) OnRangeChangedListener(com.jaygoo.widget.OnRangeChangedListener) ContextCompat(androidx.core.content.ContextCompat) DUE(com.ichi2.anki.CardBrowser.Column.DUE) Upgrade(com.ichi2.upgrade.Upgrade) CREATED(com.ichi2.anki.CardBrowser.Column.CREATED) IntentFilter(android.content.IntentFilter) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) SearchView(androidx.appcompat.widget.SearchView) INTERVAL(com.ichi2.anki.CardBrowser.Column.INTERVAL) Nullable(androidx.annotation.Nullable) CHANGED(com.ichi2.anki.CardBrowser.Column.CHANGED) Consts(com.ichi2.libanki.Consts) CardCache(com.ichi2.anki.CardBrowser.CardCache) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DECK(com.ichi2.anki.CardBrowser.Column.DECK) CARD(com.ichi2.anki.CardBrowser.Column.CARD) WarpLinearLayout(com.ichi2.ui.WarpLinearLayout) UPDATE_NOTE(com.ichi2.async.CollectionTask.TASK_TYPE.UPDATE_NOTE) NOTE_TYPE(com.ichi2.anki.CardBrowser.Column.NOTE_TYPE) TAGS(com.ichi2.anki.CardBrowser.Column.TAGS) SystemClock(android.os.SystemClock) RescheduleDialog(com.ichi2.anki.dialogs.RescheduleDialog) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) DISMISS_MULTI(com.ichi2.async.CollectionTask.TASK_TYPE.DISMISS_MULTI) Column(com.ichi2.anki.CardBrowser.Column) ArrayList(java.util.ArrayList) LAPSES(com.ichi2.anki.CardBrowser.Column.LAPSES) RENDER_BROWSER_QA(com.ichi2.async.CollectionTask.TASK_TYPE.RENDER_BROWSER_QA) SFLD(com.ichi2.anki.CardBrowser.Column.SFLD) Toast(android.widget.Toast) Menu(android.view.Menu) SimpleMessageDialog(com.ichi2.anki.dialogs.SimpleMessageDialog) REVIEWS(com.ichi2.anki.CardBrowser.Column.REVIEWS) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) EASE(com.ichi2.anki.CardBrowser.Column.EASE) CheckResult(androidx.annotation.CheckResult) TextUtils(android.text.TextUtils) Gravity(android.view.Gravity) ArrayAdapter(android.widget.ArrayAdapter) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) CardBrowserOrderDialog(com.ichi2.anki.dialogs.CardBrowserOrderDialog) CardBrowser.sCardBrowserCard(com.ichi2.anki.CardBrowser.sCardBrowserCard) LinearLayout(android.widget.LinearLayout) WindowManager(android.view.WindowManager) UNDO(com.ichi2.async.CollectionTask.TASK_TYPE.UNDO) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Permissions(com.ichi2.utils.Permissions) FunctionalInterfaces(com.ichi2.utils.FunctionalInterfaces) CheckBox(android.widget.CheckBox) Locale(java.util.Locale) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) AdapterView(android.widget.AdapterView) RecyclerView(androidx.recyclerview.widget.RecyclerView) CardBrowserMySearchesDialog(com.ichi2.anki.dialogs.CardBrowserMySearchesDialog) TabLayout(com.google.android.material.tabs.TabLayout) SEARCH_CARDS(com.ichi2.async.CollectionTask.TASK_TYPE.SEARCH_CARDS) ANSWER(com.ichi2.anki.CardBrowser.Column.ANSWER) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) AlertDialog(android.app.AlertDialog) Objects(java.util.Objects) List(java.util.List) TextView(android.widget.TextView) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) SimpleAdapter(android.widget.SimpleAdapter) OrderListAdapter(com.ichi2.anki.widgets.OrderListAdapter) RelativeLayout(android.widget.RelativeLayout) Toolbar(androidx.appcompat.widget.Toolbar) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) Context(android.content.Context) EDITED(com.ichi2.anki.CardBrowser.Column.EDITED) Intent(android.content.Intent) HashMap(java.util.HashMap) CHECK_CARD_SELECTION(com.ichi2.async.CollectionTask.TASK_TYPE.CHECK_CARD_SELECTION) Collection(com.ichi2.libanki.Collection) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) HashSet(java.util.HashSet) CardsListAdapter(com.ichi2.anki.widgets.CardsListAdapter) DeckDropDownAdapter(com.ichi2.anki.widgets.DeckDropDownAdapter) WidgetStatus(com.ichi2.widget.WidgetStatus) QUESTION(com.ichi2.anki.CardBrowser.Column.QUESTION) Utils(com.ichi2.libanki.Utils) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) Iterator(java.util.Iterator) Stats(com.ichi2.libanki.stats.Stats) PopupWindow(android.widget.PopupWindow) CollectionTask(com.ichi2.async.CollectionTask) Spinner(android.widget.Spinner) KeyBoardListenerLayout(com.ichi2.ui.KeyBoardListenerLayout) Card(com.ichi2.libanki.Card) Collections(java.util.Collections) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) AlertDialog(android.app.AlertDialog) HashMap(java.util.HashMap) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DeckDropDownAdapter(com.ichi2.anki.widgets.DeckDropDownAdapter) TaskData(com.ichi2.async.TaskData) ListPopupWindow(androidx.appcompat.widget.ListPopupWindow) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) ActionBar(androidx.appcompat.app.ActionBar) SharedPreferences(android.content.SharedPreferences) Deck(com.ichi2.libanki.Deck) JSONException(com.ichi2.utils.JSONException) SimpleAdapter(android.widget.SimpleAdapter) Intent(android.content.Intent) JSONException(com.ichi2.utils.JSONException) CardsListAdapter(com.ichi2.anki.widgets.CardsListAdapter) CardCache(com.ichi2.anki.CardBrowser.CardCache) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) CheckBox(android.widget.CheckBox) JSONObject(com.ichi2.utils.JSONObject) ArrayAdapter(android.widget.ArrayAdapter)

Example 5 with PREVIEW_CARDS

use of com.ichi2.anki.SelfStudyActivity.PREVIEW_CARDS in project AnkiChinaAndroid by ankichinateam.

the class CardBrowser method onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // (when another operation will be performed on the model, it will undo the latest operation)
    if (mUndoSnackbar != null && mUndoSnackbar.isShown()) {
        mUndoSnackbar.dismiss();
    }
    switch(item.getItemId()) {
        case android.R.id.home:
            endMultiSelectMode();
            return true;
        case R.id.action_add_note_from_card_browser:
            {
                Intent intent = new Intent(CardBrowser.this, NoteEditor.class);
                intent.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_CARDBROWSER_ADD);
                startActivityForResultWithAnimation(intent, ADD_NOTE, ActivityTransitionAnimation.LEFT);
                return true;
            }
        case R.id.action_save_search:
            {
                String searchTerms = mSearchView.getQuery().toString();
                showDialogFragment(CardBrowserMySearchesDialog.newInstance(null, mMySearchesDialogListener, searchTerms, CardBrowserMySearchesDialog.CARD_BROWSER_MY_SEARCHES_TYPE_SAVE));
                return true;
            }
        case R.id.action_list_my_searches:
            {
                JSONObject savedFiltersObj = getCol().getConf().optJSONObject("savedFilters");
                HashMap<String, String> savedFilters = new HashMap<>();
                if (savedFiltersObj != null) {
                    Iterator<String> it = savedFiltersObj.keys();
                    while (it.hasNext()) {
                        String searchName = it.next();
                        savedFilters.put(searchName, savedFiltersObj.optString(searchName));
                    }
                }
                showDialogFragment(CardBrowserMySearchesDialog.newInstance(savedFilters, mMySearchesDialogListener, "", CardBrowserMySearchesDialog.CARD_BROWSER_MY_SEARCHES_TYPE_LIST));
                return true;
            }
        case R.id.action_sort_by_size:
            showDialogFragment(CardBrowserOrderDialog.newInstance(mOrder, mOrderAsc, mOrderDialogListener));
            return true;
        case R.id.action_show_marked:
            mSearchTerms = "tag:marked";
            mSearchView.setQuery("", false);
            mSearchView.setQueryHint(getResources().getString(R.string.card_browser_show_marked));
            searchCards();
            return true;
        case R.id.action_show_suspended:
            mSearchTerms = "is:suspended";
            mSearchView.setQuery("", false);
            mSearchView.setQueryHint(getResources().getString(R.string.card_browser_show_suspended));
            searchCards();
            return true;
        case R.id.action_search_by_tag:
            showTagsDialog();
            return true;
        case R.id.action_flag_zero:
            flagTask(0);
            return true;
        case R.id.action_flag_one:
            flagTask(1);
            return true;
        case R.id.action_flag_two:
            flagTask(2);
            return true;
        case R.id.action_flag_three:
            flagTask(3);
            return true;
        case R.id.action_flag_four:
            flagTask(4);
            return true;
        case R.id.action_delete_card:
            if (mInMultiSelectMode) {
                CollectionTask.launchCollectionTask(DISMISS_MULTI, mDeleteNoteHandler, new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.DELETE_NOTE_MULTI }));
                mCheckedCards.clear();
                endMultiSelectMode();
                mCardsAdapter.notifyDataSetChanged();
            }
            return true;
        case R.id.action_mark_card:
            CollectionTask.launchCollectionTask(DISMISS_MULTI, markCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.MARK_NOTE_MULTI }));
            return true;
        case R.id.action_suspend_card:
            CollectionTask.launchCollectionTask(DISMISS_MULTI, suspendCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.SUSPEND_CARD_MULTI }));
            return true;
        case R.id.action_change_deck:
            {
                AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
                builderSingle.setTitle(getString(R.string.move_all_to_deck));
                // WARNING: changeDeck depends on this index, so any changes should be reflected there.
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.dropdown_deck_item);
                for (Deck deck : getValidDecksForChangeDeck()) {
                    try {
                        arrayAdapter.add(deck.getString("name"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                builderSingle.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        changeDeck(which);
                    }
                });
                builderSingle.show();
                return true;
            }
        case R.id.action_undo:
            if (getCol().undoAvailable()) {
                CollectionTask.launchCollectionTask(UNDO, mUndoHandler);
            }
            return true;
        case R.id.action_select_none:
            onSelectNone();
            return true;
        case R.id.action_select_all:
            onSelectAll();
            return true;
        case R.id.action_preview:
            {
                Intent previewer = new Intent(CardBrowser.this, Previewer.class);
                if (mInMultiSelectMode && checkedCardCount() > 1) {
                    // Multiple cards have been explicitly selected, so preview only those cards
                    previewer.putExtra("index", 0);
                    previewer.putExtra("cardList", getSelectedCardIds());
                } else {
                    // Preview all cards, starting from the one that is currently selected
                    int startIndex = mCheckedCards.isEmpty() ? 0 : mCheckedCards.iterator().next().getPosition();
                    previewer.putExtra("index", startIndex);
                    previewer.putExtra("cardList", getAllCardIds());
                }
                startActivityForResultWithoutAnimation(previewer, PREVIEW_CARDS);
                return true;
            }
        case R.id.action_reset_cards_progress:
            {
                Timber.i("NoteEditor:: Reset progress button pressed");
                // Show confirmation dialog before resetting card progress
                ConfirmationDialog dialog = new ConfirmationDialog();
                String title = getString(R.string.reset_card_dialog_title);
                String message = getString(R.string.reset_card_dialog_message);
                dialog.setArgs(title, message);
                Runnable confirm = () -> {
                    Timber.i("CardBrowser:: ResetProgress button pressed");
                    CollectionTask.launchCollectionTask(DISMISS_MULTI, resetProgressCardHandler(), new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.RESET_CARDS }));
                };
                dialog.setConfirm(confirm);
                showDialogFragment(dialog);
                return true;
            }
        case R.id.action_reschedule_cards:
            {
                Timber.i("CardBrowser:: Reschedule button pressed");
                long[] selectedCardIds = getSelectedCardIds();
                FunctionalInterfaces.Consumer<Integer> consumer = newDays -> CollectionTask.launchCollectionTask(DISMISS_MULTI, rescheduleCardHandler(), new TaskData(new Object[] { selectedCardIds, Collection.DismissType.RESCHEDULE_CARDS, newDays }));
                RescheduleDialog rescheduleDialog;
                if (selectedCardIds.length == 1) {
                    long cardId = selectedCardIds[0];
                    Card selected = getCol().getCard(cardId);
                    rescheduleDialog = RescheduleDialog.rescheduleSingleCard(getResources(), selected, consumer);
                } else {
                    rescheduleDialog = RescheduleDialog.rescheduleMultipleCards(getResources(), consumer, selectedCardIds.length);
                }
                showDialogFragment(rescheduleDialog);
                return true;
            }
        case R.id.action_reposition_cards:
            {
                Timber.i("CardBrowser:: Reposition button pressed");
                // Only new cards may be repositioned
                long[] cardIds = getSelectedCardIds();
                for (int i = 0; i < cardIds.length; i++) {
                    if (getCol().getCard(cardIds[i]).getQueue() != Consts.CARD_TYPE_NEW) {
                        SimpleMessageDialog dialog = SimpleMessageDialog.newInstance(getString(R.string.vague_error), getString(R.string.reposition_card_not_new_error), false);
                        showDialogFragment(dialog);
                        return false;
                    }
                }
                IntegerDialog repositionDialog = new IntegerDialog();
                repositionDialog.setArgs(getString(R.string.reposition_card_dialog_title), getString(R.string.reposition_card_dialog_message), 5);
                repositionDialog.setCallbackRunnable(days -> CollectionTask.launchCollectionTask(DISMISS_MULTI, repositionCardHandler(), new TaskData(new Object[] { cardIds, Collection.DismissType.REPOSITION_CARDS, days })));
                showDialogFragment(repositionDialog);
                return true;
            }
        case R.id.action_edit_note:
            {
                openNoteEditorForCurrentlySelectedNote();
            }
        default:
            return super.onOptionsItemSelected(item);
    }
}
Also used : AlertDialog(android.app.AlertDialog) Arrays(java.util.Arrays) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) WindowManager(android.view.WindowManager) Compat(com.ichi2.compat.Compat) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Permissions(com.ichi2.utils.Permissions) FunctionalInterfaces(com.ichi2.utils.FunctionalInterfaces) ActionBar(androidx.appcompat.app.ActionBar) Decks(com.ichi2.libanki.Decks) CheckBox(android.widget.CheckBox) Locale(java.util.Locale) Handler(android.os.Handler) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) View(android.view.View) TaskData(com.ichi2.async.TaskData) AdapterView(android.widget.AdapterView) Media(com.ichi2.libanki.Media) CardBrowserMySearchesDialog(com.ichi2.anki.dialogs.CardBrowserMySearchesDialog) Upgrade(com.ichi2.upgrade.Upgrade) IntentFilter(android.content.IntentFilter) Set(java.util.Set) SearchView(androidx.appcompat.widget.SearchView) JSONObject(com.ichi2.utils.JSONObject) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) AlertDialog(android.app.AlertDialog) Objects(java.util.Objects) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) BaseAdapter(android.widget.BaseAdapter) Consts(com.ichi2.libanki.Consts) CompatHelper(com.ichi2.compat.CompatHelper) Toolbar(androidx.appcompat.widget.Toolbar) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) ListView(android.widget.ListView) Pattern(java.util.regex.Pattern) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Snackbar(com.google.android.material.snackbar.Snackbar) Typeface(android.graphics.Typeface) Context(android.content.Context) Pair(android.util.Pair) Intent(android.content.Intent) SystemClock(android.os.SystemClock) RescheduleDialog(com.ichi2.anki.dialogs.RescheduleDialog) HashMap(java.util.HashMap) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) Collection(com.ichi2.libanki.Collection) Column(com.ichi2.anki.CardBrowser.Column) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) HashSet(java.util.HashSet) DeckDropDownAdapter(com.ichi2.anki.widgets.DeckDropDownAdapter) WidgetStatus(com.ichi2.widget.WidgetStatus) Menu(android.view.Menu) SimpleMessageDialog(com.ichi2.anki.dialogs.SimpleMessageDialog) Utils(com.ichi2.libanki.Utils) LinkedHashSet(java.util.LinkedHashSet) DialogInterface(android.content.DialogInterface) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) CheckResult(androidx.annotation.CheckResult) Iterator(java.util.Iterator) LayoutInflater(android.view.LayoutInflater) TextUtils(android.text.TextUtils) AbsListView(android.widget.AbsListView) CollectionTask(com.ichi2.async.CollectionTask) Themes(com.ichi2.themes.Themes) Spinner(android.widget.Spinner) ArrayAdapter(android.widget.ArrayAdapter) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) SECONDS_PER_DAY(com.ichi2.libanki.stats.Stats.SECONDS_PER_DAY) LanguageUtil(com.ichi2.utils.LanguageUtil) Card(com.ichi2.libanki.Card) VisibleForTesting(androidx.annotation.VisibleForTesting) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) Collections(java.util.Collections) CardBrowserOrderDialog(com.ichi2.anki.dialogs.CardBrowserOrderDialog) HashMap(java.util.HashMap) DialogInterface(android.content.DialogInterface) TaskData(com.ichi2.async.TaskData) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) RescheduleDialog(com.ichi2.anki.dialogs.RescheduleDialog) Iterator(java.util.Iterator) SimpleMessageDialog(com.ichi2.anki.dialogs.SimpleMessageDialog) Deck(com.ichi2.libanki.Deck) JSONException(com.ichi2.utils.JSONException) Intent(android.content.Intent) Card(com.ichi2.libanki.Card) JSONObject(com.ichi2.utils.JSONObject) IntegerDialog(com.ichi2.anki.dialogs.IntegerDialog) JSONObject(com.ichi2.utils.JSONObject) ArrayAdapter(android.widget.ArrayAdapter)

Aggregations

Intent (android.content.Intent)3 SharedPreferences (android.content.SharedPreferences)3 TypedValue (android.util.TypedValue)3 View (android.view.View)3 ViewGroup (android.view.ViewGroup)3 WindowManager (android.view.WindowManager)3 TextView (android.widget.TextView)3 NonNull (androidx.annotation.NonNull)3 Nullable (androidx.annotation.Nullable)3 VisibleForTesting (androidx.annotation.VisibleForTesting)3 ActivityTransitionAnimation (com.ichi2.anim.ActivityTransitionAnimation)3 TaskData (com.ichi2.async.TaskData)3 AlertDialog (android.app.AlertDialog)2 BroadcastReceiver (android.content.BroadcastReceiver)2 Context (android.content.Context)2 IntentFilter (android.content.IntentFilter)2 Bundle (android.os.Bundle)2 Handler (android.os.Handler)2 SystemClock (android.os.SystemClock)2 TextUtils (android.text.TextUtils)2