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);
}
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();
}
});
}
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();
}
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();
}
}
}
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();
}
}
Aggregations