Search in sources :

Example 1 with Toolbar

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

the class AbstractFlashcardViewer method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Timber.d("onCreate()");
    preferences = restorePreferences();
    mCardAppearance = CardAppearance.create(new ReviewerCustomFonts(this.getBaseContext()), preferences);
    super.onCreate(savedInstanceState);
    setContentView(getContentViewAttr(mPrefFullscreenReview));
    // Make ACTION_PROCESS_TEXT for in-app searching possible on > Android 4.0
    getDelegate().setHandleNativeActionModesEnabled(true);
    // initNavigationDrawer(mainView);
    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);
        // int[] attrs = new int[] {
        // R.attr.reviewStatusBarColor,
        // };
        // TypedArray ta = obtainStyledAttributes(attrs);
        // toolbar.setBackground(ta.getDrawable(0));
        mTitle = toolbar.findViewById(R.id.toolbar_title);
        mTitle.setVisibility(View.VISIBLE);
    // Decide which action to take when the navigation button is tapped.
    // toolbar.setNavigationOnClickListener(v -> onNavigationPressed());
    }
    mShortAnimDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
    mFreeVipCount = preferences.getInt("speak_count", 0);
    mVip = preferences.getBoolean(Consts.KEY_IS_VIP, false);
    mFreeOnlineEngineCount = preferences.getInt(Consts.KEY_REST_ONLINE_SPEAK_COUNT, 1000);
    // mFreeVipRecordDay = preferences.getInt("speak_count_day", 0);
    // Calendar calendar = Calendar.getInstance();
    // if (mFreeVipRecordDay != calendar.get(Calendar.DAY_OF_YEAR)) {//已经不是记录里的同一天
    // mFreeVipCount = 0;
    // preferences.edit().putInt("speak_count", mFreeVipCount)
    // .putInt("speak_count_day", calendar.get(Calendar.DAY_OF_YEAR)).apply();
    // }
    mainHandler = new Handler();
}
Also used : ReviewerCustomFonts(com.ichi2.anki.reviewer.ReviewerCustomFonts) Handler(android.os.Handler) MissingImageHandler(com.ichi2.anki.cardviewer.MissingImageHandler) Toolbar(androidx.appcompat.widget.Toolbar)

Example 2 with Toolbar

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

the class AbstractFlashcardViewer method answerCard.

protected void answerCard(@Consts.BUTTON_TYPE int ease) {
    if (mInAnswer) {
        return;
    }
    mIsSelecting = false;
    hideLookupButton();
    int buttonNumber = getCol().getSched().answerButtons(mCurrentCard);
    // Detect invalid ease for current card (e.g. by using keyboard shortcut or gesture).
    if (buttonNumber < ease) {
        return;
    }
    // Set the dots appearing below the toolbar
    switch(ease) {
        case EASE_1:
            mChosenAnswer.setText("\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, R.color.material_red_500));
            break;
        case EASE_2:
            mChosenAnswer.setText("\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, buttonNumber == Consts.BUTTON_FOUR ? R.color.material_blue_grey_600 : R.color.material_green_500));
            break;
        case EASE_3:
            mChosenAnswer.setText("\u2022\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, buttonNumber == Consts.BUTTON_FOUR ? R.color.material_green_500 : R.color.material_light_blue_500));
            break;
        case EASE_4:
            mChosenAnswer.setText("\u2022\u2022\u2022\u2022");
            mChosenAnswer.setTextColor(ContextCompat.getColor(this, R.color.material_light_blue_500));
            break;
        default:
            Timber.w("Unknown easy type %s", ease);
            break;
    }
    // remove chosen answer hint after a while
    mTimerHandler.removeCallbacks(removeChosenAnswerText);
    mTimerHandler.postDelayed(removeChosenAnswerText, mShowChosenAnswerLength);
    mSoundPlayer.stopSounds();
    stopOnlineSpeaking();
    mCurrentEase = ease;
    CollectionTask.launchCollectionTask(ANSWER_CARD, mAnswerCardHandler(true), new TaskData(mCurrentCard, mCurrentEase));
}
Also used : SuppressLint(android.annotation.SuppressLint) TaskData(com.ichi2.async.TaskData)

Example 3 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project Anki-Android by ankidroid.

the class AbstractFlashcardViewer method answerCard.

protected void answerCard(@Consts.BUTTON_TYPE int ease) {
    if (mInAnswer) {
        return;
    }
    mIsSelecting = false;
    int buttonNumber = getCol().getSched().answerButtons(mCurrentCard);
    // Detect invalid ease for current card (e.g. by using keyboard shortcut or gesture).
    if (buttonNumber < ease) {
        return;
    }
    // Temporarily sets the answer indicator dots appearing below the toolbar
    mPreviousAnswerIndicator.displayAnswerIndicator(ease, buttonNumber);
    mSoundPlayer.stopSounds();
    mCurrentEase = ease;
    new SchedulerService.AnswerAndGetCard(mCurrentCard, mCurrentEase).runWithHandler(answerCardHandler(true));
}
Also used : SchedulerService(com.ichi2.anki.servicelayer.SchedulerService) SuppressLint(android.annotation.SuppressLint)

Example 4 with Toolbar

use of com.ichi2.anki.noteeditor.Toolbar in project Anki-Android by ankidroid.

the class Reviewer method setFullScreen.

// #9332: UI Visibility -> Insets
@SuppressWarnings("deprecation")
private void setFullScreen(final AbstractFlashcardViewer a) {
    // Set appropriate flags to enable Sticky Immersive mode.
    a.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | // | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION // temporarily disabled due to #5245
    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_IMMERSIVE);
    // Show / hide the Action bar together with the status bar
    SharedPreferences prefs = AnkiDroidApp.getSharedPrefs(a);
    FullScreenMode fullscreenMode = FullScreenMode.fromPreference(prefs);
    a.getWindow().setStatusBarColor(Themes.getColorFromAttr(a, R.attr.colorPrimaryDark));
    View decorView = a.getWindow().getDecorView();
    decorView.setOnSystemUiVisibilityChangeListener(flags -> {
        final View toolbar = a.findViewById(R.id.toolbar);
        final View answerButtons = a.findViewById(R.id.answer_options_layout);
        final View topbar = a.findViewById(R.id.top_bar);
        if (toolbar == null || topbar == null || answerButtons == null) {
            return;
        }
        // Note that system bars will only be "visible" if none of the
        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
        boolean visible = (flags & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
        Timber.d("System UI visibility change. Visible: %b", visible);
        if (visible) {
            showViewWithAnimation(toolbar);
            if (fullscreenMode.equals(FullScreenMode.FULLSCREEN_ALL_GONE)) {
                showViewWithAnimation(topbar);
                showViewWithAnimation(answerButtons);
            }
        } else {
            hideViewWithAnimation(toolbar);
            if (fullscreenMode.equals(FullScreenMode.FULLSCREEN_ALL_GONE)) {
                hideViewWithAnimation(topbar);
                hideViewWithAnimation(answerButtons);
            }
        }
    });
}
Also used : SharedPreferences(android.content.SharedPreferences) FullScreenMode(com.ichi2.anki.reviewer.FullScreenMode) ImageView(android.widget.ImageView) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) AudioView(com.ichi2.anki.multimediacard.AudioView)

Example 5 with Toolbar

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

the class WebViewActivity method onCreate.

@SuppressLint({ "AddJavascriptInterface", "SetJavaScriptEnabled" })
@Override
@SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
    Themes.setThemeLegacy(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view);
    Toolbar toolbar = findViewById(R.id.toolbar);
    if (toolbar != null) {
        // toolbar.inflateMenu(R.menu.web_view);
        setSupportActionBar(toolbar);
    }
    getSupportActionBar().setTitle(getIntent().getStringExtra("url"));
    // Add a home button to the actionbar
    // getSupportActionBar().setHomeButtonEnabled(true);
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    webView = findViewById(R.id.web_view);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    // webView.getSettings().setAppCacheMaxSize(1024*1024*8);
    webView.getSettings().setUserAgentString("User-Agent:Android");
    // 可以读取文件缓存
    webView.getSettings().setAllowFileAccess(true);
    // 开启H5(APPCache)缓存功能
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    webView.getSettings().setAppCachePath(appCachePath);
    // webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
    webView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
        String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
        Request request = new Request.Builder().url(url).build();
        // 构建我们的进度监听器
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), fileName);
        final ProgressResponseBody.ProgressListener listener = (bytesRead, contentLength1, done) -> {
            // 计算百分比并更新ProgressBar
            if (contentLength1 != 0) {
                final int percent = (int) (100 * bytesRead / contentLength1);
                mProgressDialog.setProgress(percent);
            }
            if (done) {
                runOnUiThread(() -> {
                    mProgressDialog.dismiss();
                    // fixme 下载的如果不是卡牌,需要执行通用程序
                    AsyncDialogFragment newFragment = ImportDialog.newInstance(DIALOG_IMPORT_ADD_CONFIRM, file.getAbsolutePath(), WebViewActivity.this);
                    showAsyncDialogFragment(newFragment);
                });
            }
        };
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(chain -> {
            Response response = chain.proceed(chain.request());
            return response.newBuilder().body(new ProgressResponseBody(response.body(), listener)).build();
        }).build();
        // 发送响应
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) {
                Timber.i("onResponse:" + response.isSuccessful());
                writeFile(file, response);
            }
        });
        mProgressDialog = new MaterialDialog.Builder(WebViewActivity.this).title("正在下载").content("请不要做任何操作,保持屏幕常亮,切换页面或APP会导致下载中断!").progress(false, 100, false).cancelable(false).negativeText("取消下载").onNegative((dialog, which) -> {
            call.cancel();
            dialog.dismiss();
        }).show();
    });
    webView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            writeData(getIntent().getStringExtra("token"));
            WebViewActivity.this.getSupportActionBar().setTitle(title);
        }
    });
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            writeData(getIntent().getStringExtra("token"));
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Timber.i("shouldOverrideUrlLoading:%s", url);
            if (url.startsWith("openexternalbrowser://url=")) {
                // startThirdpartyApp("https://www.baidu.com");
                openUrl(Uri.parse(url.replace("openexternalbrowser://url=", "")));
            } else if (urlCanLoad(url.toLowerCase())) {
                // 加载正常网页
                view.loadUrl(url, map);
            } else {
                // 打开第三方应用或者下载apk等
                startThirdpartyApp(url);
            }
            return true;
        }
    });
    webView.setOnKeyListener((v, keyCode, event) -> {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            // 按返回键操作并且能回退网页
            if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                // 后退
                webView.goBack();
                return true;
            }
        }
        // showShareDialog();
        return false;
    });
    webView.addJavascriptInterface(new JavaScriptFunction(), "AnkiDroidJS");
    map.put("Referer", "https://file.ankichinas.cn");
    webView.loadUrl(getIntent().getStringExtra("url"), map);
}
Also used : JavascriptInterface(android.webkit.JavascriptInterface) RequiresApi(androidx.annotation.RequiresApi) UMImage(com.umeng.socialize.media.UMImage) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) AsyncDialogFragment(com.ichi2.anki.dialogs.AsyncDialogFragment) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) ColorDrawable(android.graphics.drawable.ColorDrawable) DeviceConfigInternal.context(com.umeng.socialize.utils.DeviceConfigInternal.context) Gson(com.google.gson.Gson) Map(java.util.Map) ForwardingSource(okio.ForwardingSource) WebViewClient(android.webkit.WebViewClient) ClipboardManager(android.content.ClipboardManager) View(android.view.View) TaskData(com.ichi2.async.TaskData) WebView(android.webkit.WebView) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) SHARE_MEDIA(com.umeng.socialize.bean.SHARE_MEDIA) Request(okhttp3.Request) SHOW_STUDYOPTIONS(com.ichi2.anki.DeckPicker.SHOW_STUDYOPTIONS) JSONObject(com.ichi2.utils.JSONObject) ViewGroup(android.view.ViewGroup) FileNotFoundException(java.io.FileNotFoundException) Timber(timber.log.Timber) BufferedSource(okio.BufferedSource) ShareAction(com.umeng.socialize.ShareAction) Toolbar(androidx.appcompat.widget.Toolbar) TaskListenerWithContext(com.ichi2.async.TaskListenerWithContext) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Window(android.view.Window) Context(android.content.Context) TaskListener(com.ichi2.async.TaskListener) Okio(okio.Okio) KeyEvent(android.view.KeyEvent) Source(okio.Source) DIALOG_IMPORT_ADD_CONFIRM(com.ichi2.anki.dialogs.ImportDialog.DIALOG_IMPORT_ADD_CONFIRM) Environment(android.os.Environment) UMWeb(com.umeng.socialize.media.UMWeb) ImportDialog(com.ichi2.anki.dialogs.ImportDialog) UMShareListener(com.umeng.socialize.UMShareListener) Dialog(android.app.Dialog) Intent(android.content.Intent) HashMap(java.util.HashMap) StyledProgressDialog(com.ichi2.themes.StyledProgressDialog) MenuItem(android.view.MenuItem) ClipData(android.content.ClipData) LEFT(com.ichi2.anim.ActivityTransitionAnimation.LEFT) SuppressLint(android.annotation.SuppressLint) JSONArray(com.ichi2.utils.JSONArray) WebSettings(android.webkit.WebSettings) Toast(android.widget.Toast) Menu(android.view.Menu) Response(okhttp3.Response) AnkiPackageImporter(com.ichi2.libanki.importer.AnkiPackageImporter) Call(okhttp3.Call) Callback(okhttp3.Callback) Build(android.os.Build) WebChromeClient(android.webkit.WebChromeClient) OutputStream(java.io.OutputStream) Buffer(okio.Buffer) URLUtil(android.webkit.URLUtil) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Themes(com.ichi2.themes.Themes) File(java.io.File) Color(android.graphics.Color) Gravity(android.view.Gravity) OkHttpClient(okhttp3.OkHttpClient) ActivityTransitionAnimation(com.ichi2.anim.ActivityTransitionAnimation) InputStream(java.io.InputStream) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(okhttp3.Response) Callback(okhttp3.Callback) WebChromeClient(android.webkit.WebChromeClient) AsyncDialogFragment(com.ichi2.anki.dialogs.AsyncDialogFragment) WebView(android.webkit.WebView) File(java.io.File) Toolbar(androidx.appcompat.widget.Toolbar) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

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