Search in sources :

Example 6 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project AnkiChinaAndroid by ankichinateam.

the class Preferences method initSubscreen.

private void initSubscreen(String action, PreferenceContext listener) {
    android.preference.PreferenceScreen screen;
    switch(action) {
        case "com.ichi2.anki.prefs.general":
            listener.addPreferencesFromResource(R.xml.preferences_general);
            screen = listener.getPreferenceScreen();
            if (AdaptionUtil.isRestrictedLearningDevice()) {
                android.preference.CheckBoxPreference mCheckBoxPref_Vibrate = (android.preference.CheckBoxPreference) screen.findPreference("widgetVibrate");
                android.preference.CheckBoxPreference mCheckBoxPref_Blink = (android.preference.CheckBoxPreference) screen.findPreference("widgetBlink");
                android.preference.PreferenceCategory mCategory = (android.preference.PreferenceCategory) screen.findPreference("category_general_notification_pref");
                mCategory.removePreference(mCheckBoxPref_Vibrate);
                mCategory.removePreference(mCheckBoxPref_Blink);
            }
            // Build languages
            initializeLanguageDialog(screen);
            break;
        case "com.ichi2.anki.prefs.reviewing":
            listener.addPreferencesFromResource(R.xml.preferences_reviewing);
            screen = listener.getPreferenceScreen();
            // Show error toast if the user tries to disable answer button without gestures on
            // android.preference.ListPreference fullscreenPreference = (android.preference.ListPreference)
            // screen.findPreference("fullscreenMode");
            // fullscreenPreference.setOnPreferenceChangeListener((preference, newValue) -> {
            // SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(Preferences.this);
            // if (prefs.getBoolean("gestures", false) || !"2".equals(newValue)) {
            // return true;
            // } else {
            // Toast.makeText(getApplicationContext(),
            // R.string.full_screen_error_gestures, Toast.LENGTH_LONG).show();
            // return false;
            // }
            // });
            // Custom buttons options
            android.preference.Preference customButtonsPreference = screen.findPreference("custom_buttons_link");
            customButtonsPreference.setOnPreferenceClickListener(preference -> {
                Intent i = getPreferenceSubscreenIntent(Preferences.this, "com.ichi2.anki.prefs.custom_buttons");
                startActivity(i);
                return true;
            });
            break;
        case "com.ichi2.anki.prefs.appearance":
            listener.addPreferencesFromResource(R.xml.preferences_appearance);
            screen = listener.getPreferenceScreen();
            backgroundImage = (android.preference.CheckBoxPreference) screen.findPreference("deckPickerBackground");
            backgroundImage.setOnPreferenceClickListener(preference -> {
                if (backgroundImage.isChecked()) {
                    try {
                        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
                        backgroundImage.setChecked(true);
                    } catch (Exception ex) {
                        Timber.e("%s", ex.getLocalizedMessage());
                    }
                } else {
                    backgroundImage.setChecked(false);
                    String currentAnkiDroidDirectory = CollectionHelper.getCurrentAnkiDroidDirectory(this);
                    File imgFile = new File(currentAnkiDroidDirectory, "DeckPickerBackground.png");
                    if (imgFile.exists()) {
                        if (imgFile.delete()) {
                            UIUtils.showThemedToast(this, getString(R.string.background_image_removed), false);
                        } else {
                            UIUtils.showThemedToast(this, getString(R.string.error_deleting_image), false);
                        }
                    } else {
                        UIUtils.showThemedToast(this, getString(R.string.background_image_removed), false);
                    }
                }
                return true;
            });
            initializeCustomFontsDialog(screen);
            break;
        case "com.ichi2.anki.prefs.gestures":
            listener.addPreferencesFromResource(R.xml.preferences_gestures);
            break;
        case "com.ichi2.anki.prefs.custom_controller_buttons":
            getSupportActionBar().setTitle(R.string.pref_cat_controller);
            listener.addPreferencesFromResource(R.xml.preferences_custom_controller_buttons);
            break;
        case "com.ichi2.anki.prefs.custom_buttons":
            getSupportActionBar().setTitle(R.string.custom_buttons);
            listener.addPreferencesFromResource(R.xml.preferences_custom_buttons);
            screen = listener.getPreferenceScreen();
            // Reset toolbar button customizations
            android.preference.Preference reset_custom_buttons = screen.findPreference("reset_custom_buttons");
            reset_custom_buttons.setOnPreferenceClickListener(preference -> {
                SharedPreferences.Editor edit = AnkiDroidApp.getSharedPrefs(getBaseContext()).edit();
                edit.remove("customButtonUndo");
                edit.remove("customButtonScheduleCard");
                edit.remove("customButtonMarkCard");
                edit.remove("customButtonEditCard");
                edit.remove("customButtonAddCard");
                edit.remove("customButtonReplay");
                edit.remove("customButtonSelectTts");
                edit.remove("customButtonDeckOptions");
                edit.remove("customButtonBury");
                edit.remove("customButtonSuspend");
                edit.remove("customButtonFlag");
                edit.remove("customButtonDelete");
                edit.remove("customButtonClearWhiteboard");
                edit.remove("customButtonShowHideWhiteboard");
                edit.apply();
                // TODO: Should reload the preferences screen on completion
                return true;
            });
            break;
        case "com.ichi2.anki.prefs.advanced":
            listener.addPreferencesFromResource(R.xml.preferences_advanced);
            screen = listener.getPreferenceScreen();
            // Check that input is valid before committing change in the collection path
            android.preference.EditTextPreference collectionPathPreference = (android.preference.EditTextPreference) screen.findPreference("deckPath");
            collectionPathPreference.setOnPreferenceChangeListener((preference, newValue) -> {
                final String newPath = (String) newValue;
                try {
                    CollectionHelper.initializeAnkiDroidDirectory(newPath);
                    return true;
                } catch (StorageAccessException e) {
                    Timber.e(e, "Could not initialize directory: %s", newPath);
                    Toast.makeText(getApplicationContext(), R.string.dialog_collection_path_not_dir, Toast.LENGTH_LONG).show();
                    return false;
                }
            });
            // Custom sync server option
            // android.preference.Preference customSyncServerPreference = screen.findPreference("custom_sync_server_link");
            // customSyncServerPreference.setOnPreferenceClickListener(preference -> {
            // Intent i = getPreferenceSubscreenIntent(Preferences.this,
            // "com.ichi2.anki.prefs.custom_sync_server");
            // startActivity(i);
            // return true;
            // });
            // Advanced statistics option
            android.preference.Preference advancedStatisticsPreference = screen.findPreference("advanced_statistics_link");
            advancedStatisticsPreference.setOnPreferenceClickListener(preference -> {
                Intent i = getPreferenceSubscreenIntent(Preferences.this, "com.ichi2.anki.prefs.advanced_statistics");
                startActivity(i);
                return true;
            });
            setupContextMenuPreference(screen, CardBrowserContextMenu.CARD_BROWSER_CONTEXT_MENU_PREF_KEY, R.string.card_browser_context_menu);
            setupContextMenuPreference(screen, AnkiCardContextMenu.ANKI_CARD_CONTEXT_MENU_PREF_KEY, R.string.context_menu_anki_card_label);
            // Make it possible to test crash reporting, but only for DEBUG builds
            if (BuildConfig.DEBUG && !AdaptionUtil.isUserATestClient()) {
                Timber.i("Debug mode, allowing for test crashes");
                android.preference.Preference triggerTestCrashPreference = new android.preference.Preference(this);
                triggerTestCrashPreference.setKey("trigger_crash_preference");
                triggerTestCrashPreference.setTitle("Trigger test crash");
                triggerTestCrashPreference.setSummary("Touch here for an immediate test crash");
                triggerTestCrashPreference.setOnPreferenceClickListener(preference -> {
                    Timber.w("Crash triggered on purpose from advanced preferences in debug mode");
                    throw new RuntimeException("This is a test crash");
                });
                screen.addPreference(triggerTestCrashPreference);
            }
            // Make it possible to test analytics, but only for DEBUG builds
            if (BuildConfig.DEBUG) {
                Timber.i("Debug mode, allowing for dynamic analytics config");
                android.preference.Preference analyticsDebugMode = new android.preference.Preference(this);
                analyticsDebugMode.setKey("analytics_debug_preference");
                analyticsDebugMode.setTitle("Switch Analytics to dev mode");
                analyticsDebugMode.setSummary("Touch here to use Analytics dev tag and 100% sample rate");
                analyticsDebugMode.setOnPreferenceClickListener(preference -> {
                    UsageAnalytics.setDevMode();
                    return true;
                });
                screen.addPreference(analyticsDebugMode);
            }
            if (BuildConfig.DEBUG) {
                Timber.i("Debug mode, allowing database lock preference");
                android.preference.Preference lockDbPreference = new android.preference.Preference(this);
                lockDbPreference.setKey("debug_lock_database");
                lockDbPreference.setTitle("Lock Database");
                lockDbPreference.setSummary("Touch here to lock the database (all threads block in-process, exception if using second process)");
                lockDbPreference.setOnPreferenceClickListener(preference -> {
                    DatabaseLock.engage(this);
                    return true;
                });
                screen.addPreference(lockDbPreference);
            }
            // Force full sync option
            ConfirmationPreference fullSyncPreference = (ConfirmationPreference) screen.findPreference("force_full_sync");
            fullSyncPreference.setDialogMessage(R.string.force_full_sync_summary);
            fullSyncPreference.setDialogTitle(R.string.force_full_sync_title);
            fullSyncPreference.setOkHandler(() -> {
                if (getCol() == null) {
                    Toast.makeText(getApplicationContext(), R.string.directory_inaccessible, Toast.LENGTH_LONG).show();
                    return;
                }
                getCol().modSchemaNoCheck();
                getCol().setMod();
                Toast.makeText(getApplicationContext(), android.R.string.ok, Toast.LENGTH_SHORT).show();
            });
            // Workaround preferences
            removeUnnecessaryAdvancedPrefs(screen);
            addThirdPartyAppsListener(screen);
            break;
        case "com.ichi2.anki.prefs.custom_sync_server":
            getSupportActionBar().setTitle(R.string.custom_sync_server_title);
            listener.addPreferencesFromResource(R.xml.preferences_custom_sync_server);
            screen = listener.getPreferenceScreen();
            android.preference.Preference syncUrlPreference = screen.findPreference("syncBaseUrl");
            android.preference.Preference mSyncUrlPreference = screen.findPreference("syncMediaUrl");
            syncUrlPreference.setOnPreferenceChangeListener((android.preference.Preference preference, Object newValue) -> {
                String newUrl = newValue.toString();
                if (!URLUtil.isValidUrl(newUrl)) {
                    new AlertDialog.Builder(this).setTitle(R.string.custom_sync_server_base_url_invalid).setPositiveButton(R.string.dialog_ok, null).show();
                    return false;
                }
                return true;
            });
            mSyncUrlPreference.setOnPreferenceChangeListener((android.preference.Preference preference, Object newValue) -> {
                String newUrl = newValue.toString();
                if (!URLUtil.isValidUrl(newUrl)) {
                    new AlertDialog.Builder(this).setTitle(R.string.custom_sync_server_media_url_invalid).setPositiveButton(R.string.dialog_ok, null).show();
                    return false;
                }
                return true;
            });
            break;
        case "com.ichi2.anki.prefs.advanced_statistics":
            getSupportActionBar().setTitle(R.string.advanced_statistics_title);
            listener.addPreferencesFromResource(R.xml.preferences_advanced_statistics);
            break;
    }
}
Also used : AlertDialog(android.app.AlertDialog) SharedPreferences(android.content.SharedPreferences) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) StorageAccessException(com.ichi2.anki.exception.StorageAccessException) ActivityNotFoundException(android.content.ActivityNotFoundException) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) StorageAccessException(com.ichi2.anki.exception.StorageAccessException) BadTokenException(android.view.WindowManager.BadTokenException) NumberRangePreference(com.ichi2.preferences.NumberRangePreference) ConfirmationPreference(com.ichi2.ui.ConfirmationPreference) SeekBarPreference(com.ichi2.ui.SeekBarPreference) JSONObject(com.ichi2.utils.JSONObject) File(java.io.File) ConfirmationPreference(com.ichi2.ui.ConfirmationPreference)

Example 7 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project AnkiChinaAndroid by ankichinateam.

the class DeckPicker method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.navigation_activity);
    AnkiChinaSyncer.SYNCING = false;
    // Toolbar toolbar = findViewById(R.id.toolbar);
    // if (toolbar != null) {
    // setSupportActionBar(toolbar);
    // }
    viewPager = findViewById(R.id.viewpager);
    viewPager.setUserInputEnabled(false);
    // viewPager.setScrolledListener(new CustomScrollViewPager.ScrolledListener() {
    // @Override
    // public void onScroll() {
    // openCardBrowser();
    // }
    // });
    bottomNavigationView = findViewById(R.id.navigation);
    bottomNavigationView.setItemIconTintList(null);
    BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
    mBottomAddMenuIcon = menuView.getChildAt(2).findViewById(com.google.android.material.R.id.navigation_bar_item_icon_view);
    // menuView.getItemIconSize()
    // mBottomAddMenuIcon =( (NavigationBarItemView)menuView.getChildAt(2)).setIcon();
    final ViewGroup.LayoutParams layoutParams = mBottomAddMenuIcon.getLayoutParams();
    final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 37, displayMetrics);
    layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 37, displayMetrics);
    mBottomAddMenuIcon.setLayoutParams(layoutParams);
    restoreWelcomeMessage(savedInstanceState);
    registerExternalStorageListener();
    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
    if (!preferences.contains(CONFIRM_PRIVATE_STRATEGY) && !mShowingPrivateStrategyDialog) {
        mShowingPrivateStrategyDialog = true;
        new MaterialDialog.Builder(this).title(R.string.collection_load_welcome_request_permissions_title).titleGravity(GravityEnum.CENTER).content(getClickableSpan(this)).negativeText(R.string.dialog_disagree).positiveText(R.string.dialog_agree).onPositive((innerDialog, innerWhich) -> {
            preferences.edit().putBoolean(CONFIRM_PRIVATE_STRATEGY, true).apply();
            mShowingPrivateStrategyDialog = false;
            continueActivity(preferences);
        }).positiveColor(ContextCompat.getColor(this, R.color.new_primary_color)).onNegative((innerDialog, innerWhich) -> {
            mShowingPrivateStrategyDialog = false;
            finishWithoutAnimation();
        }).negativeColor(ContextCompat.getColor(this, R.color.new_primary_text_secondary_color)).cancelable(false).canceledOnTouchOutside(false).show();
    } else {
        continueActivity(preferences);
    }
    int count = preferences.getInt(START_APP_COUNT, 0);
    count++;
    if (count == 5) {
        CustomStyleDialog customDialog = new CustomStyleDialog.Builder(this).setTitle("给个好评,鼓励一下吧!").setMessage("每一份好评对我们都是极大的鼓励,也是我们持续优化的动力").setPositiveButton("好评鼓励", (dialog, which) -> {
            dialog.dismiss();
            goAppShop(DeckPicker.this, BuildConfig.APPLICATION_ID, "");
        }).setNegativeButton("残忍拒绝", (dialog, which) -> dialog.dismiss()).create();
        customDialog.show();
    }
    preferences.edit().putInt(START_APP_COUNT, count).apply();
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) DialogHandler(com.ichi2.anki.dialogs.DialogHandler) NavigationBarItemView(com.google.android.material.navigation.NavigationBarItemView) Manifest(android.Manifest) Decks(com.ichi2.libanki.Decks) Handler(android.os.Handler) JSONException(com.ichi2.utils.JSONException) Fragment(androidx.fragment.app.Fragment) ForegroundColorSpan(android.text.style.ForegroundColorSpan) ContextCompat(androidx.core.content.ContextCompat) DeckPickerBackupNoSpaceLeftDialog(com.ichi2.anki.dialogs.DeckPickerBackupNoSpaceLeftDialog) IntentFilter(android.content.IntentFilter) StringRes(androidx.annotation.StringRes) Nullable(androidx.annotation.Nullable) Message(android.os.Message) HostNumFactory(com.ichi2.anki.web.HostNumFactory) Consts(com.ichi2.libanki.Consts) OKHttpUtil(com.ichi2.utils.OKHttpUtil) MobclickAgent(com.umeng.analytics.MobclickAgent) DeckPickerExportCompleteDialog(com.ichi2.anki.dialogs.DeckPickerExportCompleteDialog) Models(com.ichi2.libanki.Models) SimpleDateFormat(java.text.SimpleDateFormat) Dialog(android.app.Dialog) SdCardReceiver(com.ichi2.anki.receiver.SdCardReceiver) URL_PRIVATE(com.ichi2.libanki.Consts.URL_PRIVATE) ArrayList(java.util.ArrayList) CustomSyncServerUrlException(com.ichi2.libanki.sync.CustomSyncServerUrlException) SpannableStringBuilder(android.text.SpannableStringBuilder) DeckPickerNoSpaceLeftDialog(com.ichi2.anki.dialogs.DeckPickerNoSpaceLeftDialog) Calendar(java.util.Calendar) Toast(android.widget.Toast) Menu(android.view.Menu) Connection(com.ichi2.async.Connection) Response(okhttp3.Response) AnkiPackageImporter(com.ichi2.libanki.importer.AnkiPackageImporter) Call(okhttp3.Call) CHECK_MEDIA(com.ichi2.async.CollectionTask.TASK_TYPE.CHECK_MEDIA) FragmentManager(androidx.fragment.app.FragmentManager) Beta(com.tencent.bugly.beta.Beta) SpannableString(android.text.SpannableString) ALL_DECKS_ID(com.ichi2.anki.SelfStudyActivity.ALL_DECKS_ID) URL_USER_PROTOCOL(com.ichi2.libanki.Consts.URL_USER_PROTOCOL) TextUtils(android.text.TextUtils) IOException(java.io.IOException) File(java.io.File) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) EditText(android.widget.EditText) AsyncDialogFragment(com.ichi2.anki.dialogs.AsyncDialogFragment) PackageManager(android.content.pm.PackageManager) Date(java.util.Date) WindowManager(android.view.WindowManager) UnderlineSpan(android.text.style.UnderlineSpan) UsageAnalytics(com.ichi2.anki.analytics.UsageAnalytics) ClickableSpan(android.text.style.ClickableSpan) ExportDialog(com.ichi2.anki.dialogs.ExportDialog) DeviceID(com.ichi2.libanki.DeviceID) ConfirmationDialog(com.ichi2.anki.dialogs.ConfirmationDialog) Permissions(com.ichi2.utils.Permissions) AnkiChinaSyncer(com.ichi2.libanki.sync.AnkiChinaSyncer) JSONObject(org.json.JSONObject) NOT_LOGIN_ANKI_CHINA(com.ichi2.anki.MyAccount.NOT_LOGIN_ANKI_CHINA) View(android.view.View) TaskData(com.ichi2.async.TaskData) SyncStatus(com.ichi2.utils.SyncStatus) FIND_EMPTY_CARDS(com.ichi2.async.CollectionTask.TASK_TYPE.FIND_EMPTY_CARDS) ParseException(java.text.ParseException) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) BroadcastReceiver(android.content.BroadcastReceiver) DatabaseErrorDialog(com.ichi2.anki.dialogs.DatabaseErrorDialog) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) Timber(timber.log.Timber) List(java.util.List) TextView(android.widget.TextView) RelativeLayout(android.widget.RelativeLayout) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) ViewPropertyAnimator(android.view.ViewPropertyAnimator) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) VersionUtils(com.ichi2.utils.VersionUtils) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) GravityEnum(com.afollestad.materialdialogs.GravityEnum) DeckPickerAnalyticsOptInDialog(com.ichi2.anki.dialogs.DeckPickerAnalyticsOptInDialog) Intent(android.content.Intent) ViewPager2(androidx.viewpager2.widget.ViewPager2) Collection(com.ichi2.libanki.Collection) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) MenuItem(android.view.MenuItem) FragmentStateAdapter(androidx.viewpager2.adapter.FragmentStateAdapter) CHECK_DATABASE(com.ichi2.async.CollectionTask.TASK_TYPE.CHECK_DATABASE) Lifecycle(androidx.lifecycle.Lifecycle) REPAIR_COLLECTION(com.ichi2.async.CollectionTask.TASK_TYPE.REPAIR_COLLECTION) WidgetStatus(com.ichi2.widget.WidgetStatus) MotionEvent(android.view.MotionEvent) SyncErrorDialog(com.ichi2.anki.dialogs.SyncErrorDialog) Model(com.ichi2.libanki.Model) ConfirmModSchemaException(com.ichi2.anki.exception.ConfirmModSchemaException) Bugly(com.tencent.bugly.Bugly) LOAD_COLLECTION_COMPLETE(com.ichi2.async.CollectionTask.TASK_TYPE.LOAD_COLLECTION_COMPLETE) UMConfigure(com.umeng.commonsdk.UMConfigure) PlatformConfig(com.umeng.socialize.PlatformConfig) ActivityCompat(androidx.core.app.ActivityCompat) CollectionTask(com.ichi2.async.CollectionTask) BottomNavigationMenuView(com.google.android.material.bottomnavigation.BottomNavigationMenuView) Color(android.graphics.Color) MediaCheckDialog(com.ichi2.anki.dialogs.MediaCheckDialog) LOAD_DECK_COUNTS(com.ichi2.async.CollectionTask.TASK_TYPE.LOAD_DECK_COUNTS) VisibleForTesting(androidx.annotation.VisibleForTesting) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) Resources(android.content.res.Resources) CustomStyleDialog(com.ichi2.ui.CustomStyleDialog) SharedPreferences(android.content.SharedPreferences) ViewGroup(android.view.ViewGroup) SpannableStringBuilder(android.text.SpannableStringBuilder) BottomNavigationMenuView(com.google.android.material.bottomnavigation.BottomNavigationMenuView) DisplayMetrics(android.util.DisplayMetrics)

Example 8 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project AnkiChinaAndroid by ankichinateam.

the class CardBrowser 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();
    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());
    // Load reference to action bar title
    mActionBarTitle = (TextView) findViewById(R.id.toolbar_title);
    // Add drop-down menu to select deck to action bar.
    mDropDownDecks = getCol().getDecks().allSorted();
    mDropDownAdapter = new DeckDropDownAdapter(this, mDropDownDecks, R.layout.dropdown_deck_selected_item, this);
    Toolbar toolbar = findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        // 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.
        toolbar.setNavigationOnClickListener(v -> finishActivityWithFade(this, ActivityTransitionAnimation.RIGHT));
    }
    ActionBar mActionBar = getSupportActionBar();
    if (mActionBar != null) {
        mActionBar.setDisplayShowTitleEnabled(false);
    }
    mActionBarSpinner = (Spinner) findViewById(R.id.toolbar_spinner);
    mActionBarSpinner.setAdapter(mDropDownAdapter);
    mActionBarSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            deckDropDownItemChanged(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        // do nothing
        }
    });
    mActionBarSpinner.setVisibility(View.VISIBLE);
    mOrder = CARD_ORDER_NONE;
    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);
    mCards = new ArrayList<>();
    mCardsListView = (ListView) findViewById(R.id.card_browser_list);
    // Create a spinner for column1
    Spinner cardsColumn1Spinner = (Spinner) findViewById(R.id.browser_column1_spinner);
    ArrayAdapter<CharSequence> column1Adapter = ArrayAdapter.createFromResource(this, R.array.browser_column1_headings, android.R.layout.simple_spinner_item);
    column1Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    cardsColumn1Spinner.setAdapter(column1Adapter);
    mColumn1Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn1", 0);
    cardsColumn1Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // If a new column was selected then change the key used to map from mCards to the column TextView
            if (pos != mColumn1Index) {
                mColumn1Index = pos;
                AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit().putInt("cardBrowserColumn1", mColumn1Index).commit();
                Column[] fromMap = mCardsAdapter.getFromMapping();
                fromMap[0] = COLUMN1_KEYS[mColumn1Index];
                mCardsAdapter.setFromMapping(fromMap);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        // Do Nothing
        }
    });
    // Load default value for column2 selection
    mColumn2Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn2", 0);
    // Setup the column 2 heading as a spinner so that users can easily change the column type
    Spinner cardsColumn2Spinner = (Spinner) findViewById(R.id.browser_column2_spinner);
    ArrayAdapter<CharSequence> column2Adapter = ArrayAdapter.createFromResource(this, R.array.browser_column2_headings, android.R.layout.simple_spinner_item);
    column2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    cardsColumn2Spinner.setAdapter(column2Adapter);
    // Create a new list adapter with updated column map any time the user changes the column
    cardsColumn2Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // If a new column was selected then change the key used to map from mCards to the column TextView
            if (pos != mColumn2Index) {
                mColumn2Index = pos;
                AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit().putInt("cardBrowserColumn2", mColumn2Index).commit();
                Column[] fromMap = mCardsAdapter.getFromMapping();
                fromMap[1] = COLUMN2_KEYS[mColumn2Index];
                mCardsAdapter.setFromMapping(fromMap);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        // Do Nothing
        }
    });
    // get the font and font size from the preferences
    int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
    String sflCustomFont = preferences.getString("browserEditorFont", "");
    Column[] columnsContent = { COLUMN1_KEYS[mColumn1Index], COLUMN2_KEYS[mColumn2Index] };
    // make a new list adapter mapping the data in mCards to column1 and column2 of R.layout.card_item_browser
    mCardsAdapter = new MultiColumnListAdapter(this, R.layout.card_item_browser, columnsContent, new int[] { R.id.card_sfld, R.id.card_column2 }, sflRelativeFontSize, sflCustomFont);
    // link the adapter to the main mCardsListView
    mCardsListView.setAdapter(mCardsAdapter);
    // make the items (e.g. question & answer) render dynamically when scrolling
    mCardsListView.setOnScrollListener(new RenderOnScroll());
    // set the spinner index
    cardsColumn1Spinner.setSelection(mColumn1Index);
    cardsColumn2Spinner.setSelection(mColumn2Index);
    mCardsListView.setOnItemClickListener(new ListView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (mInMultiSelectMode) {
                // click on whole cell triggers select
                CheckBox cb = (CheckBox) view.findViewById(R.id.card_checkbox);
                cb.toggle();
                onCheck(position, view);
            } else {
                // load up the card selected on the list
                long clickedCardId = getCards().get(position).getId();
                openNoteEditorForCard(clickedCardId);
            }
        }
    });
    mCardsListView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long id) {
            mLastSelectedPosition = position;
            loadMultiSelectMode();
            // click on whole cell triggers select
            CheckBox cb = (CheckBox) view.findViewById(R.id.card_checkbox);
            cb.toggle();
            onCheck(position, view);
            recenterListView(view);
            mCardsAdapter.notifyDataSetChanged();
            return true;
        }
    });
    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());
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) Spinner(android.widget.Spinner) View(android.view.View) AdapterView(android.widget.AdapterView) SearchView(androidx.appcompat.widget.SearchView) TextView(android.widget.TextView) ListView(android.widget.ListView) AbsListView(android.widget.AbsListView) DeckDropDownAdapter(com.ichi2.anki.widgets.DeckDropDownAdapter) ListView(android.widget.ListView) AbsListView(android.widget.AbsListView) Column(com.ichi2.anki.CardBrowser.Column) CheckBox(android.widget.CheckBox) OnItemSelectedListener(android.widget.AdapterView.OnItemSelectedListener) ActionBar(androidx.appcompat.app.ActionBar) Toolbar(androidx.appcompat.widget.Toolbar)

Example 9 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project AnkiChinaAndroid by ankichinateam.

the class TagsDialog method adjustToolbar.

private void adjustToolbar(View tagsDialogView) {
    Toolbar mToolbar = tagsDialogView.findViewById(R.id.tags_dialog_toolbar);
    mToolbar.setTitle(mDialogTitle);
    mToolbar.inflateMenu(R.menu.tags_dialog_menu);
    final InputFilter addTagFilter = (source, start, end, dest, dstart, dend) -> {
        for (int i = start; i < end; i++) {
            if (source.charAt(i) == ' ') {
                return "";
            }
        }
        return null;
    };
    MenuItem mToolbarAddItem = mToolbar.getMenu().findItem(R.id.tags_dialog_action_add);
    mToolbarAddItem.setOnMenuItemClickListener(menuItem -> {
        String query = mToolbarSearchView.getQuery().toString();
        if (mToolbarSearchItem.isActionViewExpanded() && !TextUtils.isEmpty(query)) {
            addTag(query);
            mToolbarSearchView.setQuery("", true);
        } else {
            MaterialDialog.Builder addTagBuilder = new MaterialDialog.Builder(getActivity()).title(getString(R.string.add_tag)).negativeText(R.string.dialog_cancel).positiveText(R.string.dialog_ok).inputType(InputType.TYPE_CLASS_TEXT).input(R.string.tag_name, R.string.empty_string, (dialog, input) -> addTag(input.toString()));
            final MaterialDialog addTagDialog = addTagBuilder.build();
            EditText inputET = addTagDialog.getInputEditText();
            inputET.setFilters(new InputFilter[] { addTagFilter });
            addTagDialog.show();
        }
        return true;
    });
    mToolbarSearchItem = mToolbar.getMenu().findItem(R.id.tags_dialog_action_filter);
    mToolbarSearchView = (SearchView) mToolbarSearchItem.getActionView();
    EditText queryET = mToolbarSearchView.findViewById(R.id.search_src_text);
    queryET.setFilters(new InputFilter[] { addTagFilter });
    mToolbarSearchView.setQueryHint(getString(R.string.filter_tags));
    mToolbarSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            mToolbarSearchView.clearFocus();
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            TagsArrayAdapter adapter = (TagsArrayAdapter) mTagsListRecyclerView.getAdapter();
            adapter.getFilter().filter(newText);
            return true;
        }
    });
    MenuItem checkAllItem = mToolbar.getMenu().findItem(R.id.tags_dialog_action_select_all);
    checkAllItem.setOnMenuItemClickListener(menuItem -> {
        boolean changed = false;
        if (mCurrentTags.containsAll(mTagsArrayAdapter.mTagsList)) {
            mCurrentTags.removeAll(mTagsArrayAdapter.mTagsList);
            changed = true;
        } else {
            for (String tag : mTagsArrayAdapter.mTagsList) {
                if (!mCurrentTags.contains(tag)) {
                    mCurrentTags.add(tag);
                    changed = true;
                }
            }
        }
        if (changed) {
            mTagsArrayAdapter.notifyDataSetChanged();
        }
        return true;
    });
    switch(mType) {
        case TYPE_ADD_TAG:
            mToolbarSearchView.setQueryHint(getString(R.string.add_new_filter_tags));
            break;
        default:
            mToolbarAddItem.setVisible(false);
            break;
    }
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) AnalyticsDialogFragment(com.ichi2.anki.analytics.AnalyticsDialogFragment) WindowManager(android.view.WindowManager) R(com.ichi2.anki.R) Filter(android.widget.Filter) Dialog(android.app.Dialog) RadioGroup(android.widget.RadioGroup) TreeSet(java.util.TreeSet) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) UIUtils(com.ichi2.anki.UIUtils) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) LayoutInflater(android.view.LayoutInflater) InputType(android.text.InputType) TextUtils(android.text.TextUtils) SearchView(androidx.appcompat.widget.SearchView) ViewGroup(android.view.ViewGroup) List(java.util.List) TextView(android.widget.TextView) CheckedTextView(android.widget.CheckedTextView) Toolbar(androidx.appcompat.widget.Toolbar) Filterable(android.widget.Filterable) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) InputFilter(android.text.InputFilter) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Collections(java.util.Collections) EditText(android.widget.EditText) Resources(android.content.res.Resources) EditText(android.widget.EditText) InputFilter(android.text.InputFilter) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) MenuItem(android.view.MenuItem) SearchView(androidx.appcompat.widget.SearchView) Toolbar(androidx.appcompat.widget.Toolbar)

Aggregations

View (android.view.View)5 SharedPreferences (android.content.SharedPreferences)4 TextView (android.widget.TextView)4 Toolbar (androidx.appcompat.widget.Toolbar)4 Dialog (android.app.Dialog)3 Intent (android.content.Intent)3 Bundle (android.os.Bundle)3 TextUtils (android.text.TextUtils)3 MenuItem (android.view.MenuItem)3 ViewGroup (android.view.ViewGroup)3 NonNull (androidx.annotation.NonNull)3 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)3 TaskData (com.ichi2.async.TaskData)3 File (java.io.File)3 SuppressLint (android.annotation.SuppressLint)2 Context (android.content.Context)2 Resources (android.content.res.Resources)2 Color (android.graphics.Color)2 ColorDrawable (android.graphics.drawable.ColorDrawable)2 Uri (android.net.Uri)2