use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.
the class CardEditor method setNote.
private void setNote(Note note) {
try {
if (note == null) {
mCurrentDid = mCol.getDecks().current().getLong("id");
if (mCol.getDecks().isDyn(mCurrentDid)) {
mCurrentDid = 1;
}
JSONObject model = mCol.getModels().current();
mEditorNote = new Note(mCol, model);
mEditorNote.model().put("did", mCurrentDid);
mModelButton.setText(getResources().getString(R.string.CardEditorModel, model.getString("name")));
JSONArray tags = model.getJSONArray("tags");
for (int i = 0; i < tags.length(); i++) {
mEditorNote.addTag(tags.getString(i));
}
} else {
mEditorNote = note;
mCurrentDid = mCurrentEditedCard.getDid();
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCurrentTags = mEditorNote.getTags();
updateDeck();
updateTags();
populateEditFields();
swapText(true);
}
use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.
the class CardEditor method onCreateDialog.
@Override
protected Dialog onCreateDialog(int id) {
StyledDialog dialog = null;
Resources res = getResources();
StyledDialog.Builder builder = new StyledDialog.Builder(this);
switch(id) {
case DIALOG_TAGS_SELECT:
builder.setTitle(R.string.card_details_tags);
builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mAddNote) {
try {
JSONArray ja = new JSONArray();
for (String t : selectedTags) {
ja.put(t);
}
mCol.getModels().current().put("tags", ja);
mCol.getModels().setChanged();
} catch (JSONException e) {
throw new RuntimeException(e);
}
mEditorNote.setTags(selectedTags);
}
mCurrentTags = selectedTags;
updateTags();
}
});
builder.setNegativeButton(res.getString(R.string.cancel), null);
mNewTagEditText = (EditText) new EditText(this);
mNewTagEditText.setHint(R.string.add_new_tag);
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (source.charAt(i) == ' ' || source.charAt(i) == ',') {
return "";
}
}
return null;
}
};
mNewTagEditText.setFilters(new InputFilter[] { filter });
ImageView mAddTextButton = new ImageView(this);
mAddTextButton.setImageResource(R.drawable.ic_addtag);
mAddTextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tag = mNewTagEditText.getText().toString();
if (tag.length() != 0) {
if (mEditorNote.hasTag(tag)) {
mNewTagEditText.setText("");
return;
}
selectedTags.add(tag);
actualizeTagDialog(mTagsDialog);
mNewTagEditText.setText("");
}
}
});
FrameLayout frame = new FrameLayout(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
params.rightMargin = 10;
mAddTextButton.setLayoutParams(params);
frame.addView(mNewTagEditText);
frame.addView(mAddTextButton);
builder.setView(frame, false, true);
dialog = builder.create();
mTagsDialog = dialog;
break;
case DIALOG_DECK_SELECT:
ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>();
// Use this array to know which ID is associated with each
// Item(name)
final ArrayList<Long> dialogDeckIds = new ArrayList<Long>();
ArrayList<JSONObject> decks = mCol.getDecks().all();
Collections.sort(decks, new JSONNameComparator());
builder.setTitle(R.string.deck);
for (JSONObject d : decks) {
try {
if (d.getInt("dyn") == 0) {
dialogDeckItems.add(d.getString("name"));
dialogDeckIds.add(d.getLong("id"));
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// Convert to Array
String[] items = new String[dialogDeckItems.size()];
dialogDeckItems.toArray(items);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
long newId = dialogDeckIds.get(item);
if (mCurrentDid != newId) {
if (mAddNote) {
try {
// TODO: mEditorNote.setDid(newId);
mEditorNote.model().put("did", newId);
mCol.getModels().setChanged();
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
mCurrentDid = newId;
updateDeck();
}
}
});
dialog = builder.create();
mDeckSelectDialog = dialog;
break;
case DIALOG_MODEL_SELECT:
ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
// Use this array to know which ID is associated with each
// Item(name)
final ArrayList<Long> dialogIds = new ArrayList<Long>();
ArrayList<JSONObject> models = mCol.getModels().all();
Collections.sort(models, new JSONNameComparator());
builder.setTitle(R.string.note_type);
for (JSONObject m : models) {
try {
dialogItems.add(m.getString("name"));
dialogIds.add(m.getLong("id"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// Convert to Array
String[] items2 = new String[dialogItems.size()];
dialogItems.toArray(items2);
builder.setItems(items2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
long oldModelId;
try {
oldModelId = mCol.getModels().current().getLong("id");
} catch (JSONException e) {
throw new RuntimeException(e);
}
long newId = dialogIds.get(item);
if (oldModelId != newId) {
mCol.getModels().setCurrent(mCol.getModels().get(newId));
JSONObject cdeck = mCol.getDecks().current();
try {
cdeck.put("mid", newId);
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCol.getDecks().save(cdeck);
int size = mEditFields.size();
String[] oldValues = new String[size];
for (int i = 0; i < size; i++) {
oldValues[i] = mEditFields.get(i).getText().toString();
}
setNote();
resetEditFields(oldValues);
mTimerHandler.removeCallbacks(checkDuplicatesRunnable);
duplicateCheck(false);
}
}
});
dialog = builder.create();
break;
case DIALOG_RESET_CARD:
builder.setTitle(res.getString(R.string.reset_card_dialog_title));
builder.setMessage(res.getString(R.string.reset_card_dialog_message));
builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// for (long cardId :
// mDeck.getCardsFromFactId(mEditorNote.getId())) {
// mDeck.cardFromId(cardId).resetCard();
// }
// mDeck.reset();
// setResult(Reviewer.RESULT_EDIT_CARD_RESET);
// mCardReset = true;
// Themes.showThemedToast(CardEditor.this,
// getResources().getString(
// R.string.reset_card_dialog_confirmation), true);
}
});
builder.setNegativeButton(res.getString(R.string.no), null);
builder.setCancelable(true);
dialog = builder.create();
break;
case DIALOG_INTENT_INFORMATION:
dialog = createDialogIntentInformation(builder, res);
}
return dialog;
}
use of com.ichi2.utils.JSONException in project Anki-Android by Ramblurr.
the class CardBrowser method updateCardInList.
private void updateCardInList(Card card, String updatedCardTags) {
Note note = card.note();
int pos;
for (Card c : note.cards()) {
pos = getPosition(mCards, c.getId());
if (pos < 0 || pos >= mCards.size()) {
continue;
}
if (updatedCardTags != null) {
mCards.get(pos).put("tags", updatedCardTags);
}
String sfld = note.getSFld();
mCards.get(pos).put("sfld", sfld);
if (mWholeCollection) {
String deckName;
try {
deckName = mCol.getDecks().get(card.getDid()).getString("name");
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCards.get(pos).put("deck", deckName);
}
String flags = Integer.toString((c.getQueue() == -1 ? 1 : 0) + (note.hasTag("marked") ? 2 : 0));
mCards.get(pos).put("flags", flags);
}
updateList();
}
use of com.ichi2.utils.JSONException in project AnkiChinaAndroid by ankichinateam.
the class SelfStudyActivity 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.screen:
showScreenDialog();
return true;
case R.id.action_edit:
mCardsAdapter.setMultiCheckable(!mCardsAdapter.isMultiCheckableMode());
return true;
case R.id.action_add_note_from_card_browser:
{
Intent intent = new Intent(SelfStudyActivity.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_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 (inMultiSelectMode()) {
CollectionTask.launchCollectionTask(DISMISS_MULTI, mDeleteNoteHandler, new TaskData(new Object[] { getSelectedCardIds(), Collection.DismissType.DELETE_NOTE_MULTI }));
mCardsAdapter.getSelectedItemIds().clear();
}
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 }));
toggleMultiSelectMode(false);
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), (dialog, which) -> dialog.dismiss());
builderSingle.setAdapter(arrayAdapter, (dialog, 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_preview:
{
mStartStudyButton.performClick();
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);
}
}
use of com.ichi2.utils.JSONException 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();
}
});
}
Aggregations