Search in sources :

Example 1 with CustomStyleDialog

use of com.ichi2.ui.CustomStyleDialog in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method readCardText.

private void readCardText(final Card card, final SoundSide cardSide) {
    final String cardSideContent;
    if (!cardContentIsEmpty() && ((sDisplayAnswer && mFinalLoadAnswer.isEmpty()) || (!sDisplayAnswer && mFinalLoadQuestion.isEmpty()))) {
        mainHandler.postDelayed(() -> {
            showProgressBar();
            Toast.makeText(AbstractFlashcardViewer.this, "卡牌加载中,网络不佳", Toast.LENGTH_SHORT).show();
        }, 3000);
        nNeedSpeakFinalRenderContent = true;
        if (!fetchingRenderContent) {
            fetchWebViewRenderContent(mCardWebView);
        }
        return;
    }
    mainHandler.removeCallbacksAndMessages(null);
    hideProgressBar();
    // 在这里获取最后的内容
    cardSideContent = cardSide == SoundSide.QUESTION ? mFinalLoadQuestion : mFinalLoadAnswer;
    Timber.i("finally i wanna say:%s,showing answer:%s", cardSideContent, sDisplayAnswer);
    // 如果不是设置了离线模式且当前没网时,且非强制离线模式,则默认使用在线模式
    if (AnkiDroidApp.getSharedPrefs(this).getBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false) && !mOfflineSpeakingForOnce) {
        // 使用在线语音引擎
        File target = new File(FileUtil.createTmpDir(this), card.getId() + "-" + cardSide + ".wav");
        Timber.i("target audio :%s", target.getAbsolutePath());
        if (target.exists()) {
            Timber.i("target audio is exists,play it now");
            mSoundPlayer.playSound(target.getAbsolutePath(), mp -> mOnlineSpeaking = false);
            mOnlineSpeaking = true;
            speakingHandler.postDelayed(speakingRunnable, 300);
            return;
        }
        if (!isNetworkAvailable(AbstractFlashcardViewer.this)) {
            CustomStyleDialog customStyleDialog = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this).setCustomLayout(R.layout.dialog_common_custom_next).setTitle("在线朗读需联网!").centerTitle().setMessage("没有网络时可以点下方按钮切换成本地引擎").setPositiveButton("切换本地引擎", (dialog, which) -> {
                dialog.dismiss();
                AnkiDroidApp.getSharedPrefs(this).edit().putBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false).apply();
            }).create();
            customStyleDialog.show();
            return;
        }
        getAccount().getToken(this, new MyAccount.TokenCallback() {

            @Override
            public void onSuccess(String token) {
                mCacheToken = token;
                // if (mFreeOnlineEngineCount != -10086) {
                // if (mFreeOnlineEngineCount > 0) {
                // String voice=ReadText.getAzureLanguage(card.getDid(), card.getOrd(), cardSide);
                // if (voice.isEmpty()) {
                // //选择语言
                // CustomStyleDialog d = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this)
                // .setCustomLayout(R.layout.dialog_common_custom_next)
                // .setTitle("首次朗读,请设置语言")
                // .centerTitle()
                // .setMessage("设置语言后,朗读效果更优,还可以选择是否自动朗读。")
                // .setPositiveButton("前往设置", (dialog, which) -> {
                // dialog.dismiss();
                // SpeakSettingActivity.OpenSpeakSetting(card.getId(), card.getDid(), AbstractFlashcardViewer.this);
                // })  .create();
                // d.show();
                // return;
                // }
                List<Pair<String, String>> texts = splitAry(cardSideContent, 59, String.valueOf(card.getId()), cardSide);
                Map<String, String> params = new HashMap<>();
                params.put(SpeechSynthesizer.PARAM_SPEED, String.valueOf(ReadText.getSpeechRate(mCurrentCard.getDid(), mCurrentCard.getOrd()) * 5));
                synthesizer.setParams(params);
                int result = synthesizer.batchSpeak(texts);
                checkResult(result, "speak");
            // 
            // } else {
            // CustomStyleDialog customStyleDialog = new CustomStyleDialog.Builder(AbstractFlashcardViewer.this)
            // .setCustomLayout(R.layout.dialog_common_custom_next)
            // .setTitle("在线朗读次数已用完")
            // .centerTitle()
            // .setMessage("请前往充值在线朗读次数,学霸用户可以切换离线引擎,不限朗读次数")
            // .setPositiveButton("前往充值", (dialog, which) -> {
            // dialog.dismiss();
            // WebViewActivity.openUrlInApp(AbstractFlashcardViewer.this, String.format(mBuyOnlineEngineUrl, token, BuildConfig.VERSION_NAME), token, REFRESH_VOICE_INFO);
            // }).setNegativeButton("使用离线引擎", (dialog, which) -> {
            // dialog.dismiss();
            // AnkiDroidApp.getSharedPrefs(AbstractFlashcardViewer.this).edit().putBoolean(KEY_SELECT_ONLINE_SPEAK_ENGINE, false).apply();
            // })
            // 
            // .create();
            // 
            // customStyleDialog.show();
            // }
            // } else {
            // updateOnlineVoiceInfo(token);
            // }
            }

            @Override
            public void onFail(String message) {
                Timber.e("need login while using online speak engine ");
                Toast.makeText(AbstractFlashcardViewer.this, "当前未使用Anki记忆卡账号登录,无法使用在线语音引擎", Toast.LENGTH_SHORT).show();
                Intent myAccount = new Intent(AbstractFlashcardViewer.this, MyAccount.class);
                myAccount.putExtra("notLoggedIn", true);
                startActivityForResultWithAnimation(myAccount, REFRESH_VOICE_INFO, ActivityTransitionAnimation.FADE);
            }
        });
        speakingHandler.postDelayed(speakingRunnable, 300);
        return;
    }
    mOfflineSpeakingForOnce = false;
    String clozeReplacement = this.getString(R.string.reviewer_tts_cloze_spoken_replacement);
    ReadText.readCardSide(cardSide, cardSideContent, card.getId(), getDeckIdForCard(card), card.getOrd(), clozeReplacement, true);
    speakingHandler.postDelayed(speakingRunnable, 300);
}
Also used : JavascriptInterface(android.webkit.JavascriptInterface) UI_PLAY_END(com.ichi2.bd.MainHandlerConstant.UI_PLAY_END) Version(com.github.zafarkhaja.semver.Version) Bundle(android.os.Bundle) TagsDialog(com.ichi2.anki.dialogs.TagsDialog) JsResult(android.webkit.JsResult) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) AbstractSched(com.ichi2.libanki.sched.AbstractSched) RangeSeekBar(com.jaygoo.widget.RangeSeekBar) RenderProcessGoneDetail(android.webkit.RenderProcessGoneDetail) HitTestResult(android.webkit.WebView.HitTestResult) ActionBar(androidx.appcompat.app.ActionBar) FileSaveListener(com.ichi2.bd.FileSaveListener) Decks(com.ichi2.libanki.Decks) Matcher(java.util.regex.Matcher) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) JSONException(com.ichi2.utils.JSONException) THEME_NIGHT_BLACK(com.ichi2.themes.Themes.THEME_NIGHT_BLACK) OnRangeChangedListener(com.jaygoo.widget.OnRangeChangedListener) ContextCompat(androidx.core.content.ContextCompat) TargetApi(android.annotation.TargetApi) Log(android.util.Log) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ConnectivityManager(android.net.ConnectivityManager) HtmlUtils(com.ichi2.utils.HtmlUtils) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) TtsMode(com.baidu.tts.client.TtsMode) IntentFilter(android.content.IntentFilter) CardMarker(com.ichi2.anki.reviewer.CardMarker) Set(java.util.Set) JSONObject(com.ichi2.utils.JSONObject) BE_VIP(com.ichi2.anki.DeckPicker.BE_VIP) IdRes(androidx.annotation.IdRes) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Message(android.os.Message) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) CompatHelper(com.ichi2.compat.CompatHelper) WebViewDebugging(com.ichi2.utils.WebViewDebugging) DiffEngine(com.ichi2.utils.DiffEngine) TypedAnswer(com.ichi2.anki.cardviewer.TypedAnswer) WebResourceResponse(android.webkit.WebResourceResponse) Dialog(android.app.Dialog) SystemClock(android.os.SystemClock) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) CardAppearance.calculateDynamicFontSize(com.ichi2.anki.cardviewer.CardAppearance.calculateDynamicFontSize) ViewAnimation(com.ichi2.anim.ViewAnimation) ArrayList(java.util.ArrayList) REFRESH_VOICE_INFO(com.ichi2.anki.DeckPicker.REFRESH_VOICE_INFO) WebResourceRequest(android.webkit.WebResourceRequest) Toast(android.widget.Toast) Menu(android.view.Menu) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) Call(okhttp3.Call) CardAppearance(com.ichi2.anki.cardviewer.CardAppearance) WebChromeClient(android.webkit.WebChromeClient) LinkedHashSet(java.util.LinkedHashSet) PRINT(com.ichi2.bd.MainHandlerConstant.PRINT) CheckResult(androidx.annotation.CheckResult) MissingImageHandler(com.ichi2.anki.cardviewer.MissingImageHandler) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) IOException(java.io.IOException) SoundSide(com.ichi2.libanki.Sound.SoundSide) File(java.io.File) Gravity(android.view.Gravity) Lock(java.util.concurrent.locks.Lock) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) FileUtil(com.ichi2.utils.FileUtil) Configuration(android.content.res.Configuration) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) SpeechSynthesizerListener(com.baidu.tts.client.SpeechSynthesizerListener) ImageButton(android.widget.ImageButton) REQUEST_CODE_SPEAK_SETTING(com.ichi2.anki.SpeakSettingActivity.REQUEST_CODE_SPEAK_SETTING) LinearLayout(android.widget.LinearLayout) URLDecoder(java.net.URLDecoder) HtmlColors(com.ichi2.themes.HtmlColors) GestureDetectorCompat(androidx.core.view.GestureDetectorCompat) WindowManager(android.view.WindowManager) NonBlockSyntherizer(com.ichi2.bd.NonBlockSyntherizer) FormBody(okhttp3.FormBody) ByteArrayInputStream(java.io.ByteArrayInputStream) ViewerCommand(com.ichi2.anki.cardviewer.ViewerCommand) Gson(com.google.gson.Gson) Locale(java.util.Locale) WebViewClient(android.webkit.WebViewClient) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) WebView(android.webkit.WebView) InitConfig(com.ichi2.bd.InitConfig) Auth(com.ichi2.bd.Auth) SimpleOnGestureListener(android.view.GestureDetector.SimpleOnGestureListener) SynthesizerTool(com.baidu.tts.client.SynthesizerTool) BroadcastReceiver(android.content.BroadcastReceiver) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) IOfflineResourceConst(com.ichi2.bd.IOfflineResourceConst) MySyntherizer(com.ichi2.bd.MySyntherizer) List(java.util.List) TextView(android.widget.TextView) ActivityNotFoundException(android.content.ActivityNotFoundException) SpeechSynthesizer(com.baidu.tts.client.SpeechSynthesizer) KEY_SELECT_ONLINE_SPEAK_ENGINE(com.ichi2.libanki.Consts.KEY_SELECT_ONLINE_SPEAK_ENGINE) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) THEME_NIGHT_DARK(com.ichi2.themes.Themes.THEME_NIGHT_DARK) OfflineResource(com.ichi2.bd.OfflineResource) AudioView(com.ichi2.anki.multimediacard.AudioView) Pattern(java.util.regex.Pattern) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) EditorInfo(android.view.inputmethod.EditorInfo) Snackbar(com.google.android.material.snackbar.Snackbar) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Note(com.ichi2.libanki.Note) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) UI_CHANGE_SYNTHES_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_SYNTHES_TEXT_SELECTION) KeyEvent(android.view.KeyEvent) Pair(android.util.Pair) Intent(android.content.Intent) ReviewerCustomFonts(com.ichi2.anki.reviewer.ReviewerCustomFonts) HashMap(java.util.HashMap) REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML(com.ichi2.anki.DeckPicker.REFRESH_LOGIN_STATE_AND_TURN_TO_VIP_HTML) Collection(com.ichi2.libanki.Collection) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) RequestBody(okhttp3.RequestBody) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) HashSet(java.util.HashSet) ConnectivityManagerCompat(androidx.core.net.ConnectivityManagerCompat) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) MotionEvent(android.view.MotionEvent) Build(android.os.Build) WeakReference(java.lang.ref.WeakReference) LinkedList(java.util.LinkedList) Sound(com.ichi2.libanki.Sound) Utils(com.ichi2.libanki.Utils) LoggerProxy(com.baidu.tts.chainofresponsibility.logger.LoggerProxy) Consumer(com.ichi2.utils.FunctionalInterfaces.Consumer) Function(com.ichi2.utils.FunctionalInterfaces.Function) UI_CHANGE_INPUT_TEXT_SELECTION(com.ichi2.bd.MainHandlerConstant.UI_CHANGE_INPUT_TEXT_SELECTION) FlagDef(com.ichi2.anki.reviewer.CardMarker.FlagDef) LayoutInflater(android.view.LayoutInflater) ReviewerUi(com.ichi2.anki.reviewer.ReviewerUi) CollectionTask(com.ichi2.async.CollectionTask) Chronometer(android.widget.Chronometer) Themes(com.ichi2.themes.Themes) Template(com.ichi2.libanki.template.Template) Color(android.graphics.Color) WebResourceError(android.webkit.WebResourceError) UI_PLAY_START(com.ichi2.bd.MainHandlerConstant.UI_PLAY_START) AdaptionUtil(com.ichi2.utils.AdaptionUtil) Card(com.ichi2.libanki.Card) Activity(android.app.Activity) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) OnClickListener(android.view.View.OnClickListener) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Intent(android.content.Intent) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with CustomStyleDialog

use of com.ichi2.ui.CustomStyleDialog 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 3 with CustomStyleDialog

use of com.ichi2.ui.CustomStyleDialog in project AnkiChinaAndroid by ankichinateam.

the class StudyOptionsFragment method configMaxDayLearnAndRev.

private void configMaxDayLearnAndRev() {
    CustomStyleDialog customDialog = new CustomStyleDialog.Builder(getAnkiActivity()).setTitle("设置每天学习量").setCustomLayout(R.layout.dialog_common_custom_next).setMultiEditorModeCallback(new CustomStyleDialog.Builder.MultiEditorModeCallback() {

        @Override
        public String[] getEditorText() {
            // return new String[] {mOptions.getJSONObject("new").getString("perDay"), mOptions.getJSONObject("rev").getString("perDay"),};
            return new String[] { "30", "200" };
        }

        @Override
        public String[] getEditorHint() {
            return new String[] { "每天新卡上限", "每天复习上限" };
        }

        @Override
        public String[] getItemHint() {
            return new String[] { "学习一段时间后,未来每天新卡+复习卡约180张,大约需30分钟", "建议设置为最大9999,有多少复习多少" };
        }
    }).addSingleTextChangedListener(new CustomStyleDialog.Builder.MyTextWatcher() {

        @Override
        public void beforeTextChanged(Dialog dialog, CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(Dialog dialog, CharSequence s, int start, int before, int count) {
            if (s.toString().isEmpty()) {
                ((CustomStyleDialog) dialog).getSingleEditorModeHintView().setText("未来每天学习量=新卡数x6");
            } else {
                int num = 0;
                try {
                    num = Integer.parseInt(s.toString()) * 6;
                } catch (Exception ignored) {
                }
                int time = num * 10 / 60;
                ((CustomStyleDialog) dialog).getSingleEditorModeHintView().setText(String.format("学习一段时间后,未来每天新卡+复习卡约%s张,大约需%s分钟", num, time));
            }
        }

        @Override
        public void afterTextChanged(Dialog dialog, Editable s) {
        }
    }).setPositiveButton("进入学习", (dialog, which) -> {
        String text1 = ((CustomStyleDialog) dialog).getMultiEditor().get(0).getText().toString();
        String text2 = ((CustomStyleDialog) dialog).getMultiEditor().get(1).getText().toString();
        int maxNewCard = 0;
        int maxRevCard = 0;
        try {
            maxNewCard = Integer.parseInt(text1);
        } catch (Exception ignored) {
        }
        try {
            maxRevCard = Integer.parseInt(text2);
        } catch (Exception ignored) {
        }
        if (maxNewCard >= 0 && maxNewCard <= 9999 && maxRevCard >= 0 && maxRevCard <= 9999) {
            mOptions.getJSONObject("new").put("perDay", maxNewCard);
            mOptions.getJSONObject("rev").put("perDay", maxRevCard);
            Timber.i("edit new and rev max:" + maxNewCard + "," + maxRevCard);
            try {
                getCol().getDecks().save(mOptions);
            } catch (RuntimeException e) {
                Timber.e(e, "DeckOptions - RuntimeException on saving conf");
                AnkiDroidApp.sendExceptionReport(e, "DeckOptionsSaveConf");
            }
            refreshOption();
            dialog.dismiss();
            openReviewerInternal();
        } else {
            UIUtils.showThemedToast(getAnkiActivity(), "请填写0至9999之间的数值", false);
        }
    }).setNegativeButton("跳过", (dialog, which) -> {
        dialog.dismiss();
        try {
            getCol().getDecks().save(mOptions);
        } catch (RuntimeException e) {
            Timber.e(e, "DeckOptions - RuntimeException on saving conf");
            AnkiDroidApp.sendExceptionReport(e, "DeckOptionsSaveConf");
        }
        refreshOption();
        openReviewerInternal();
    }).create();
    customDialog.show();
}
Also used : DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) Bundle(android.os.Bundle) TypeToken(com.google.gson.reflect.TypeToken) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Maps(java8.util.Maps) KEY_STOPPED(com.ichi2.anki.StudySettingActivity.KEY_STOPPED) DeckInfoListAdapter(com.ichi2.anki.widgets.DeckInfoListAdapter) Decks(com.ichi2.libanki.Decks) Gson(com.google.gson.Gson) Locale(java.util.Locale) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) RecyclerView(androidx.recyclerview.widget.RecyclerView) REQUEST_BROWSE_CARDS(com.ichi2.anki.DeckPicker.REQUEST_BROWSE_CARDS) TabLayout(com.google.android.material.tabs.TabLayout) TYPE_LIFE(com.ichi2.libanki.stats.Stats.AxisType.TYPE_LIFE) SHOW_STUDYOPTIONS(com.ichi2.anki.DeckPicker.SHOW_STUDYOPTIONS) Set(java.util.Set) FragmentTransaction(androidx.fragment.app.FragmentTransaction) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) DeckPickerContextMenu(com.ichi2.anki.dialogs.DeckPickerContextMenu) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) NextCardHandler(com.ichi2.anki.AbstractFlashcardViewer.NextCardHandler) ALL_DECKS_ID(com.ichi2.libanki.stats.Stats.ALL_DECKS_ID) CompatHelper(com.ichi2.compat.CompatHelper) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) Snackbar(com.google.android.material.snackbar.Snackbar) DialogFragment(androidx.fragment.app.DialogFragment) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Dialog(android.app.Dialog) Intent(android.content.Intent) StepsPreference.convertToJSON(com.ichi2.preferences.StepsPreference.convertToJSON) HashMap(java.util.HashMap) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) PixelFormat(android.graphics.PixelFormat) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray) Menu(android.view.Menu) Utils(com.ichi2.libanki.Utils) AbstractDeckTreeNode(com.ichi2.libanki.sched.AbstractDeckTreeNode) Stats(com.ichi2.libanki.stats.Stats) LayoutInflater(android.view.LayoutInflater) CollectionTask(com.ichi2.async.CollectionTask) Color(android.graphics.Color) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) TreeMap(java.util.TreeMap) KEY_MIND_MODE(com.ichi2.anki.StudySettingActivity.KEY_MIND_MODE) CustomStudyDialog(com.ichi2.anki.dialogs.CustomStudyDialog) DeckPicker.fadeOut(com.ichi2.anki.DeckPicker.fadeOut) Activity(android.app.Activity) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) DeckPicker.fadeIn(com.ichi2.anki.DeckPicker.fadeIn) STUDY_SETTING(com.ichi2.anki.StudySettingActivity.STUDY_SETTING) EditText(android.widget.EditText) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Dialog(android.app.Dialog) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) CustomStudyDialog(com.ichi2.anki.dialogs.CustomStudyDialog) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Editable(android.text.Editable)

Example 4 with CustomStyleDialog

use of com.ichi2.ui.CustomStyleDialog in project AnkiChinaAndroid by ankichinateam.

the class ReadText method selectTtsForVip.

public static void selectTtsForVip(String text, long cid, long did, int ord, Sound.SoundSide qa, boolean vipSpeak) {
    Timber.w("selectTts:%s", vipSpeak);
    // TODO: Consolidate with ReadText.readCardSide
    mTextToSpeak = text;
    mQuestionAnswer = qa;
    mDid = did;
    mOrd = ord;
    Resources res = mReviewer.get().getResources();
    final MaterialDialog.Builder builder = new MaterialDialog.Builder(mReviewer.get());
    // Build the language list if it's empty
    if (availableTtsLocales.isEmpty()) {
        buildAvailableLanguages(TextToSpeech.LANG_AVAILABLE);
    }
    if (availableTtsLocales.size() == 0) {
        Timber.w("ReadText.textToSpeech() no TTS languages available");
        builder.content(res.getString(R.string.no_tts_available_message)).iconAttr(R.attr.dialogErrorIcon).positiveText(res.getString(R.string.dialog_ok));
    } else {
        if (vipSpeak) {
            for (int i = 0; i < availableTtsLocales.size(); i++) {
                // vip里的设置,默认选择中文
                String name = availableTtsLocales.get(i).getDisplayName();
                if (name.contains("chinese") || name.contains("Chinese") || name.contains("中文") || name.contains("中国")) {
                    // 默认选择中文
                    String locale = availableTtsLocales.get(i).getISO3Language();
                    // if (!locale.equals(NO_TTS)) {
                    // speak(mTextToSpeak, locale, TextToSpeech.QUEUE_FLUSH);
                    // }
                    MetaDB.storeLanguage(mReviewer.get(), mDid, mOrd, mQuestionAnswer, locale);
                    return;
                }
            }
            CustomStyleDialog d = new CustomStyleDialog.Builder(mReviewer.get()).setCustomLayout(R.layout.dialog_common_custom_next).setTitle("首次朗读,请设置语言").centerTitle().setMessage("设置语言后,朗读效果更优,还可以选择是否自动朗读。").setPositiveButton("前往设置", (dialog, which) -> {
                dialog.dismiss();
                SpeakSettingActivity.OpenSpeakSetting(cid, did, mReviewer.get());
            }).create();
            d.show();
        }
    }
}
Also used : Context(android.content.Context) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) WindowManager(android.view.WindowManager) UtteranceProgressListener(android.speech.tts.UtteranceProgressListener) Compat(com.ichi2.compat.Compat) Timber(timber.log.Timber) ArrayList(java.util.ArrayList) TextToSpeech(android.speech.tts.TextToSpeech) Nullable(androidx.annotation.Nullable) Locale(java.util.Locale) Handler(android.os.Handler) Toast(android.widget.Toast) CompatHelper(com.ichi2.compat.CompatHelper) View(android.view.View) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) WeakReference(java.lang.ref.WeakReference) Snackbar(com.google.android.material.snackbar.Snackbar) VisibleForTesting(androidx.annotation.VisibleForTesting) Sound(com.ichi2.libanki.Sound) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources)

Example 5 with CustomStyleDialog

use of com.ichi2.ui.CustomStyleDialog in project AnkiChinaAndroid by ankichinateam.

the class StudyOptionsFragment method openReviewer.

private void openReviewer() {
    if (mShouldConfigBeforeStudy && mOptions != null) {
        SharedPreferences sharedPreferences = getAnkiActivity().getSharedPreferences(STUDY_SETTING, 0);
        StringBuilder initIds = new StringBuilder(sharedPreferences.getString(KEY_CONFIG_INIT, ""));
        if (initIds.length() > 0) {
            String[] ids = initIds.toString().split(",");
            if (ids.length > 0) {
                for (String id : ids) {
                    if (getCol().getDecks().current().getLong("id") == Long.parseLong(id)) {
                        // 已经初始化过了,直接跳过
                        openReviewerInternal();
                        return;
                    }
                }
            }
        // 没初始化过,那现在也初始化了。
        // initIds.append(",");
        }
        for (long id : getDeckIds(getCol().getDecks().current().getLong("id"), getCol())) {
            if (!initIds.toString().isEmpty()) {
                initIds.append(",");
            }
            initIds.append(id);
        }
        // initIds += Stats.deckLimit(getCol().getDecks().current().getLong("id"), getCol()).replace("(","").replace(")","").trim();//要把子牌组也加入里面
        sharedPreferences.edit().putString(KEY_CONFIG_INIT, initIds.toString()).apply();
        String savedMindModeValue = sharedPreferences.getString(KEY_MIND_MODE, "");
        Map<String, Integer> map = null;
        try {
            Gson gson = new Gson();
            map = gson.fromJson(savedMindModeValue, new TypeToken<Map<String, Integer>>() {
            }.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String mDeckIdStr = String.valueOf(getCol().getDecks().current().getLong("id"));
        mCurrentMindModeValue = map != null && map.get(mDeckIdStr) != null ? map.get(mDeckIdStr) : 0;
        if (mMindModeValues == null) {
            mMindModeValues = getResources().getStringArray(R.array.mind_mode_values);
            mMindModeLabels = getResources().getStringArray(R.array.mind_mode_labels);
            mMindModeHints = getResources().getStringArray(R.array.mind_mode_hint);
            for (int i = 0; i < mMindModeValues.length; i++) {
                mMindModeMap.put(Integer.valueOf(mMindModeValues[i]), mMindModeLabels[i]);
            }
        }
        CustomStyleDialog customDialog = new CustomStyleDialog.Builder(getAnkiActivity()).setTitle("记忆模式").setCustomLayout(R.layout.dialog_common_custom_next).setSelectListModeCallback(new CustomStyleDialog.Builder.SelectListModeCallback() {

            @Override
            public String[] getItemContent() {
                return mMindModeLabels;
            }

            @Override
            public String[] getItemHint() {
                return mMindModeHints;
            }

            @Override
            public int getDefaultSelectedPosition() {
                return mCurrentMindModeValue;
            }

            @Override
            public void onItemSelect(int position) {
                mCurrentMindModeValue = position;
            }
        }).setPositiveButton("下一步", (dialog, which) -> {
            String oldValue = sharedPreferences.getString(KEY_MIND_MODE, "");
            Map<String, Integer> oldMap = null;
            Gson gson = new Gson();
            try {
                oldMap = gson.fromJson(oldValue, new TypeToken<Map<String, Integer>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (oldMap == null) {
                oldMap = new HashMap<>();
            }
            for (long id : getDeckIds(getCol().getDecks().current().getLong("id"), getCol())) {
                // Timber.i("看看都是什么id %s", id);
                oldMap.put(String.valueOf(id), mCurrentMindModeValue);
            }
            String newValue = gson.toJson(oldMap);
            sharedPreferences.edit().putString(KEY_MIND_MODE, newValue).apply();
            CollectionTask.launchCollectionTask(CONF_RESET, new ConfChangeHandler(StudyOptionsFragment.this, mCurrentMindModeValue), // 先恢复默认,即长记模式
            new TaskData(new Object[] { mOptions }));
            dialog.dismiss();
        }).setNegativeButton("跳过", (dialog, which) -> {
            dialog.dismiss();
            try {
                getCol().getDecks().save(mOptions);
            } catch (RuntimeException e) {
                Timber.e(e, "DeckOptions - RuntimeException on saving conf");
                AnkiDroidApp.sendExceptionReport(e, "DeckOptionsSaveConf");
            }
            refreshOption();
            openReviewerInternal();
        }).create();
        customDialog.show();
    } else {
        openReviewerInternal();
    }
}
Also used : DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) Bundle(android.os.Bundle) TypeToken(com.google.gson.reflect.TypeToken) Deck(com.ichi2.libanki.Deck) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Maps(java8.util.Maps) KEY_STOPPED(com.ichi2.anki.StudySettingActivity.KEY_STOPPED) DeckInfoListAdapter(com.ichi2.anki.widgets.DeckInfoListAdapter) Decks(com.ichi2.libanki.Decks) Gson(com.google.gson.Gson) Locale(java.util.Locale) Handler(android.os.Handler) DeckConfig(com.ichi2.libanki.DeckConfig) Map(java.util.Map) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Button(android.widget.Button) TaskData(com.ichi2.async.TaskData) RecyclerView(androidx.recyclerview.widget.RecyclerView) REQUEST_BROWSE_CARDS(com.ichi2.anki.DeckPicker.REQUEST_BROWSE_CARDS) TabLayout(com.google.android.material.tabs.TabLayout) TYPE_LIFE(com.ichi2.libanki.stats.Stats.AxisType.TYPE_LIFE) SHOW_STUDYOPTIONS(com.ichi2.anki.DeckPicker.SHOW_STUDYOPTIONS) Set(java.util.Set) FragmentTransaction(androidx.fragment.app.FragmentTransaction) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) DeckPickerContextMenu(com.ichi2.anki.dialogs.DeckPickerContextMenu) List(java.util.List) Nullable(androidx.annotation.Nullable) TextView(android.widget.TextView) NextCardHandler(com.ichi2.anki.AbstractFlashcardViewer.NextCardHandler) ALL_DECKS_ID(com.ichi2.libanki.stats.Stats.ALL_DECKS_ID) CompatHelper(com.ichi2.compat.CompatHelper) Toolbar(androidx.appcompat.widget.Toolbar) RelativeLayout(android.widget.RelativeLayout) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) Snackbar(com.google.android.material.snackbar.Snackbar) DialogFragment(androidx.fragment.app.DialogFragment) KEY_SHOW_TTS_ICON(com.ichi2.libanki.Consts.KEY_SHOW_TTS_ICON) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Dialog(android.app.Dialog) Intent(android.content.Intent) StepsPreference.convertToJSON(com.ichi2.preferences.StepsPreference.convertToJSON) HashMap(java.util.HashMap) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) PixelFormat(android.graphics.PixelFormat) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) MenuItem(android.view.MenuItem) TASK_TYPE(com.ichi2.async.CollectionTask.TASK_TYPE) ArrayList(java.util.ArrayList) JSONArray(com.ichi2.utils.JSONArray) Menu(android.view.Menu) Utils(com.ichi2.libanki.Utils) AbstractDeckTreeNode(com.ichi2.libanki.sched.AbstractDeckTreeNode) Stats(com.ichi2.libanki.stats.Stats) LayoutInflater(android.view.LayoutInflater) CollectionTask(com.ichi2.async.CollectionTask) Color(android.graphics.Color) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) TreeMap(java.util.TreeMap) KEY_MIND_MODE(com.ichi2.anki.StudySettingActivity.KEY_MIND_MODE) CustomStudyDialog(com.ichi2.anki.dialogs.CustomStudyDialog) DeckPicker.fadeOut(com.ichi2.anki.DeckPicker.fadeOut) Activity(android.app.Activity) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) DeckPicker.fadeIn(com.ichi2.anki.DeckPicker.fadeIn) STUDY_SETTING(com.ichi2.anki.StudySettingActivity.STUDY_SETTING) EditText(android.widget.EditText) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) SharedPreferences(android.content.SharedPreferences) Gson(com.google.gson.Gson) TaskData(com.ichi2.async.TaskData) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Aggregations

View (android.view.View)7 CustomStyleDialog (com.ichi2.ui.CustomStyleDialog)7 Context (android.content.Context)6 SharedPreferences (android.content.SharedPreferences)6 Bundle (android.os.Bundle)6 Handler (android.os.Handler)6 WindowManager (android.view.WindowManager)6 NonNull (androidx.annotation.NonNull)6 Timber (timber.log.Timber)6 Dialog (android.app.Dialog)5 Intent (android.content.Intent)5 Resources (android.content.res.Resources)5 TypedArray (android.content.res.TypedArray)5 Uri (android.net.Uri)5 TypedValue (android.util.TypedValue)5 Gravity (android.view.Gravity)5 Menu (android.view.Menu)5 MenuItem (android.view.MenuItem)5 ViewGroup (android.view.ViewGroup)5 RelativeLayout (android.widget.RelativeLayout)5