Example usage for android.graphics.drawable Drawable setBounds

List of usage examples for android.graphics.drawable Drawable setBounds

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable setBounds.

Prototype

public void setBounds(int left, int top, int right, int bottom) 

Source Link

Document

Specify a bounding rectangle for the Drawable.

Usage

From source file:com.justwayward.reader.ui.activity.ReadActivity.java

private void changedMode(boolean isNight, int position) {
    SharedPreferencesUtil.getInstance().putBoolean(Constant.ISNIGHT, isNight);
    AppCompatDelegate//from   w w  w .j ava  2 s .c om
            .setDefaultNightMode(isNight ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);

    if (position >= 0) {
        curTheme = position;
    } else {
        curTheme = SettingManager.getInstance().getReadTheme();
    }
    gvAdapter.select(curTheme);

    mPageWidget.setTheme(isNight ? ThemeManager.NIGHT : curTheme);
    mPageWidget.setTextColor(
            ContextCompat.getColor(mContext,
                    isNight ? R.color.chapter_content_night : R.color.chapter_content_day),
            ContextCompat.getColor(mContext,
                    isNight ? R.color.chapter_title_night : R.color.chapter_title_day));

    mTvBookReadMode.setText(getString(isNight ? R.string.book_read_mode_day_manual_setting
            : R.string.book_read_mode_night_manual_setting));
    Drawable drawable = ContextCompat.getDrawable(this,
            isNight ? R.drawable.ic_menu_mode_day_manual : R.drawable.ic_menu_mode_night_manual);
    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    mTvBookReadMode.setCompoundDrawables(null, drawable, null, null);

    ThemeManager.setReaderTheme(curTheme, mRlBookReadRoot);
}

From source file:com.tpos.widget.pagertab.PagerSlidingTabStrip.java

private void updateTabStyles() {

    for (int i = 0; i < tabCount; i++) {

        View v = tabsContainer.getChildAt(i);

        v.setBackgroundResource(tabBackgroundResId);

        if (v instanceof TextView) {

            TextView tab = (TextView) v;
            tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
            tab.setTypeface(tabTypeface, tabTypefaceStyle);
            tab.setTextColor(tabTextColor);

            // setAllCaps() is only available from API 14, so the upper case is made manually if we are on a
            // pre-ICS-build
            if (textAllCaps) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    tab.setAllCaps(true);
                } else {
                    tab.setText(tab.getText().toString().toUpperCase(locale));
                }/*from  w  w w.jav  a2 s  .  com*/
            }
        }

        // steven add
        if (pager.getAdapter() instanceof IconTextTabProvider) {
            if (v instanceof TextView) {
                Drawable tDrawable = null;
                try {
                    tDrawable = getResources()
                            .getDrawable(((IconTextTabProvider) pager.getAdapter()).getPageIconResId(i));
                } catch (NotFoundException e) {
                    e.printStackTrace();
                    tDrawable = null;
                }
                if (tDrawable != null) {
                    tDrawable.setBounds(0, 0, (int) (tDrawable.getIntrinsicWidth() * 0.5),
                            (int) (tDrawable.getIntrinsicHeight() * 0.5));
                    ((TextView) v).setCompoundDrawables(null, tDrawable, null, null);
                }
            }
        }
    }

}

From source file:com.example.carlitos.swipeitemrecycler.view.animation.swipe_item.swipeable.RemovingItemDecorator.java

private void fillSwipingItemBackground(Canvas c, Drawable drawable, float scale) {
    final Rect bounds = mSwipingItemBounds;
    final int translationX = mTranslationX;
    final int translationY = mTranslationY;
    final float hScale = (mHorizontal) ? 1.0f : scale;
    final float vScale = (mHorizontal) ? scale : 1.0f;

    int width = (int) (hScale * bounds.width() + 0.5f);
    int height = (int) (vScale * bounds.height() + 0.5f);

    if ((height == 0) || (width == 0) || (drawable == null)) {
        return;//from www  .  j  a  v  a2s . c om
    }

    final int savedCount = c.save();

    c.clipRect(bounds.left + translationX, bounds.top + translationY, bounds.left + translationX + width,
            bounds.top + translationY + height);

    // c.drawColor(0xffff0000); // <-- debug

    c.translate(bounds.left + translationX - (bounds.width() - width) / 2,
            bounds.top + translationY - (bounds.height() - height) / 2);
    drawable.setBounds(0, 0, bounds.width(), bounds.height());

    drawable.draw(c);

    c.restoreToCount(savedCount);
}

From source file:de.grobox.liberario.activities.MapActivity.java

private Bitmap getBitmap(Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
            Bitmap.Config.ARGB_8888);/* ww  w  .  java 2  s.  c  om*/
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);
    return bitmap;
}

From source file:com.android.incallui.CallCardFragment.java

/**
 * Converts a drawable into a bitmap.// w w w. j  ava  2 s . c  om
 *
 * @param drawable the drawable to be converted.
 */
public static Bitmap drawableToBitmap(Drawable drawable) {
    Bitmap bitmap;
    if (drawable instanceof BitmapDrawable) {
        bitmap = ((BitmapDrawable) drawable).getBitmap();
    } else {
        if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
            // Needed for drawables that are just a colour.
            bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                    Bitmap.Config.ARGB_8888);
        }

        Log.i(TAG, "Created bitmap with width " + bitmap.getWidth() + ", height " + bitmap.getHeight());

        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
    }
    return bitmap;
}

From source file:com.likemag.cordova.inappbrowsercustom.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from  w  w  w.ja v  a2 s.c o m*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        @SuppressLint("NewApi")
        public void run() {
            // Let's create the main dialog
            dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setInAppBroswer(getInAppBrowser());

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.WHITE);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            Resources activityRes = cordova.getActivity().getResources();
            int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable backIcon = activityRes.getDrawable(backResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                back.setBackgroundDrawable(backIcon);
            } else {
                back.setBackground(backIcon);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable fwdIcon = activityRes.getDrawable(fwdResId);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                forward.setBackgroundDrawable(fwdIcon);
            } else {
                forward.setBackground(fwdIcon);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close/Done button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setText(getPostName());
            close.setTextSize(20.0f);
            close.setTextColor(android.graphics.Color.GRAY);
            close.setId(5);
            int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable",
                    cordova.getActivity().getPackageName());
            Drawable closeIcon = activityRes.getDrawable(backResId);
            closeIcon.setBounds(0, 0, 40, 40);
            close.setPadding(0, 0, 0, 0);
            close.setBackgroundDrawable(null);
            close.setCompoundDrawables(closeIcon, null, null, null);
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
                //close.setBackgroundDrawable(closeIcon);
            } else {
                //close.setBackground(closeIcon);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(android.webkit.WebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                CookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                CookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            //toolbar.addView(actionButtonContainer);
            //toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.keylesspalace.tusky.activity.ComposeActivity.java

private void setStatusVisibility(String visibility) {
    statusVisibility = visibility;//w  ww .  ja v a 2 s  .  c o  m
    switch (visibility) {
    case "public": {
        floatingBtn.setText(R.string.action_send_public);
        floatingBtn.setCompoundDrawables(null, null, null, null);
        break;
    }
    case "private": {
        floatingBtn.setText(R.string.action_send);
        Drawable lock = AppCompatResources.getDrawable(this, R.drawable.send_private);
        if (lock != null) {
            lock.setBounds(0, 0, lock.getIntrinsicWidth(), lock.getIntrinsicHeight());
            floatingBtn.setCompoundDrawables(null, null, lock, null);
        }
        break;
    }
    default: {
        floatingBtn.setText(R.string.action_send);
        floatingBtn.setCompoundDrawables(null, null, null, null);
        break;
    }
    }
}

From source file:com.nononsenseapps.feeder.model.ImageTextLoader.java

/**
 *
 * @return a Drawable with a youtube logo in the center
 *///  ww w  .j  a  va  2  s  .  c  o m
protected Drawable getYoutubeThumb(final com.nononsenseapps.text.VideoTagHunter.Video video) {
    Drawable[] layers = new Drawable[2];

    int w1, h1;
    try {
        //final Bitmap b = p.load(video.imageurl).tag(ImageTextLoader.this).get();
        final Bitmap b = g.load(video.imageurl).asBitmap().fitCenter().into(maxSize.x, maxSize.y).get();
        //final Point newSize = scaleImage(b.getWidth(), b.getHeight());
        w1 = b.getWidth();
        h1 = b.getHeight();
        final BitmapDrawable d = new BitmapDrawable(getContext().getResources(), b);
        Log.d("JONASYOUTUBE", "Bounds: " + d.getIntrinsicWidth() + ", " + "" + d.getIntrinsicHeight() + " vs "
                + w1 + ", " + h1);
        // Settings bounds later
        //d.setBounds(0, 0, w1, h1);
        // Set in layer
        layers[0] = d;
    } catch (InterruptedException | ExecutionException e) {
        Log.e("JONASYOUTUBE", "" + e.getMessage());
        throw new NullPointerException(e.getLocalizedMessage());
    }

    // Add layer with play icon
    final Drawable playicon = getContext().getResources().getDrawable(R.drawable.youtube_icon);
    // 20% size, in middle
    int w2 = playicon.getIntrinsicWidth();
    int h2 = playicon.getIntrinsicHeight();

    final double ratio = ((double) h2) / ((double) w2);

    // Start with width which is known
    final double relSize = 0.2;
    w2 = (int) (relSize * w1);
    final int left = (int) (((double) (w1 - w2)) / 2.0);
    // Then height is simple
    h2 = (int) (ratio * w2);
    final int top = (int) (((double) (h1 - h2)) / 2.0);

    Log.d("JONASYOUTUBE", "l t w h: " + left + " " + top + " " + w2 + " " + h2);

    // And add to layer
    layers[1] = playicon;
    final LayerDrawable ld = new LayerDrawable(layers);
    // Need to set bounds on outer drawable first as it seems to override
    // child bounds
    ld.setBounds(0, 0, w1, h1);
    // Now set smaller bounds on youtube icon
    playicon.setBounds(left, top, left + w2, top + h2);
    return ld;
}

From source file:am.widget.indicatortabstrip.IndicatorTabStrip.java

/**
 * /*  w  w w  .j a  v  a2  s  . co  m*/
 *
 * @param canvas     
 * @param position   ???
 * @param itemWidth  ?
 * @param itemHeight ?
 */
protected void drawItemBackground(Canvas canvas, int position, int itemWidth, int itemHeight) {
    if (!hasItemBackgrounds())
        return;
    Drawable tag = getItemBackground(position);
    if (position == getItemCount() - 1) {
        int restWidth = getLastItemWidth();
        tag.setBounds(0, 0, restWidth, itemHeight);
    } else {
        tag.setBounds(0, 0, itemWidth, itemHeight);
    }
    final float moveX = ViewCompat.getPaddingStart(this) + (itemWidth + getIntervalWidth()) * position;
    final float moveY = getPaddingTop();
    canvas.save();
    canvas.translate(moveX, moveY);
    tag.draw(canvas);
    canvas.restore();
}

From source file:de.gebatzens.sia.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(SIAApp.SIA_APP.school.getTheme());
    super.onCreate(savedInstanceState);
    Log.w("ggvp", "CREATE NEW MAINACTIVITY");
    //Debug.startMethodTracing("sia3");
    SIAApp.SIA_APP.activity = this;
    savedState = savedInstanceState;/*from w  w  w .jav  a  2s  .c om*/

    final FragmentData.FragmentList fragments = SIAApp.SIA_APP.school.fragments;

    Intent intent = getIntent();
    if (intent != null && intent.getStringExtra("fragment") != null) {
        FragmentData frag = fragments
                .getByType(FragmentData.FragmentType.valueOf(intent.getStringExtra("fragment"))).get(0);
        SIAApp.SIA_APP.setFragmentIndex(fragments.indexOf(frag));
    }

    if (intent != null && intent.getBooleanExtra("reload", false)) {
        SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));
        intent.removeExtra("reload");
    }

    setContentView(R.layout.activity_main);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    mContent = getFragment();
    transaction.replace(R.id.content_fragment, mContent, "gg_content_fragment");
    transaction.commit();

    Log.d("ggvp", "DATA: " + fragments.get(SIAApp.SIA_APP.getFragmentIndex()).getData());
    if (fragments.get(SIAApp.SIA_APP.getFragmentIndex()).getData() == null)
        SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));

    if ("Summer".equals(SIAApp.SIA_APP.getCurrentThemeName())) {
        ImageView summerNavigationPalm = (ImageView) findViewById(R.id.summer_navigation_palm);
        summerNavigationPalm.setImageResource(R.drawable.summer_palm);
        ImageView summerBackgroundImage = (ImageView) findViewById(R.id.summer_background_image);
        summerBackgroundImage.setImageResource(R.drawable.summer_background);
    }

    mToolBar = (Toolbar) findViewById(R.id.toolbar);
    mToolBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {

            switch (menuItem.getItemId()) {
            case R.id.action_refresh:
                ((SwipeRefreshLayout) mContent.getView().findViewById(R.id.refresh)).setRefreshing(true);
                SIAApp.SIA_APP.refreshAsync(new Runnable() {
                    @Override
                    public void run() {
                        ((SwipeRefreshLayout) mContent.getView().findViewById(R.id.refresh))
                                .setRefreshing(false);
                    }
                }, true, fragments.get(SIAApp.SIA_APP.getFragmentIndex()));
                return true;
            case R.id.action_settings:
                Intent i = new Intent(MainActivity.this, SettingsActivity.class);
                startActivityForResult(i, 1);
                return true;
            case R.id.action_addToCalendar:
                showExamDialog();
                return true;
            case R.id.action_help:
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getApplication().getString(R.string.help));
                builder.setMessage(getApplication().getString(R.string.exam_explain));
                builder.setPositiveButton(getApplication().getString(R.string.close),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                return true;
            }

            return false;
        }
    });

    updateToolbar(SIAApp.SIA_APP.school.name, fragments.get(SIAApp.SIA_APP.getFragmentIndex()).name);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        SIAApp.SIA_APP.setStatusBarColorTransparent(getWindow()); // because of the navigation drawer
    }

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolBar, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.addDrawerListener(mDrawerToggle);
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    mNavigationHeader = navigationView.getHeaderView(0);
    mNavigationSchoolpictureText = (TextView) mNavigationHeader.findViewById(R.id.drawer_image_text);
    mNavigationSchoolpictureText.setText(SIAApp.SIA_APP.school.name);
    mNavigationSchoolpicture = (ImageView) mNavigationHeader.findViewById(R.id.navigation_schoolpicture);
    mNavigationSchoolpicture.setImageBitmap(SIAApp.SIA_APP.school.loadImage());
    mNavigationSchoolpictureLink = mNavigationHeader.findViewById(R.id.navigation_schoolpicture_link);
    mNavigationSchoolpictureLink.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewIn) {
            mDrawerLayout.closeDrawers();
            Intent linkIntent = new Intent(Intent.ACTION_VIEW);
            linkIntent.setData(Uri.parse(SIAApp.SIA_APP.school.website));
            startActivity(linkIntent);
        }
    });

    final Menu menu = navigationView.getMenu();
    menu.clear();
    for (int i = 0; i < fragments.size(); i++) {
        MenuItem item = menu.add(R.id.fragments, Menu.NONE, i, fragments.get(i).name);
        item.setIcon(fragments.get(i).getIconRes());
    }

    menu.add(R.id.settings, R.id.settings_item, fragments.size(), R.string.settings);
    menu.setGroupCheckable(R.id.fragments, true, true);
    menu.setGroupCheckable(R.id.settings, false, false);

    final Menu navMenu = navigationView.getMenu();
    selectedItem = SIAApp.SIA_APP.getFragmentIndex();
    if (selectedItem != -1)
        navMenu.getItem(selectedItem).setChecked(true);

    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            if (menuItem.getItemId() == R.id.settings_item) {
                mDrawerLayout.closeDrawers();
                Intent i = new Intent(MainActivity.this, SettingsActivity.class);
                startActivityForResult(i, 1);
            } else {
                final int index = menuItem.getOrder();
                if (SIAApp.SIA_APP.getFragmentIndex() != index) {
                    SIAApp.SIA_APP.setFragmentIndex(index);
                    menuItem.setChecked(true);
                    updateToolbar(SIAApp.SIA_APP.school.name, menuItem.getTitle().toString());
                    mContent = getFragment();
                    Animation fadeOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);
                    fadeOut.setAnimationListener(new Animation.AnimationListener() {

                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            FrameLayout contentFrame = (FrameLayout) findViewById(R.id.content_fragment);
                            contentFrame.setVisibility(View.INVISIBLE);
                            if (fragments.get(index).getData() == null)
                                SIAApp.SIA_APP.refreshAsync(null, true, fragments.get(index));

                            //removeAllFragments();

                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            transaction.replace(R.id.content_fragment, mContent, "gg_content_fragment");
                            transaction.commit();

                            snowView.updateSnow();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    FrameLayout contentFrame = (FrameLayout) findViewById(R.id.content_fragment);
                    contentFrame.startAnimation(fadeOut);
                    mDrawerLayout.closeDrawers();
                } else {
                    mDrawerLayout.closeDrawers();
                }
            }
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= 25) {
        ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
        shortcutManager.removeAllDynamicShortcuts();

        for (int i = 0; i < fragments.size(); i++) {
            Drawable drawable = getDrawable(fragments.get(i).getIconRes());
            Bitmap icon;
            if (drawable instanceof VectorDrawable) {
                icon = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                        Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(icon);
                drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                drawable.draw(canvas);
            } else {
                icon = BitmapFactory.decodeResource(getResources(), fragments.get(i).getIconRes());
            }

            Bitmap connectedIcon = Bitmap.createBitmap(icon.getWidth(), icon.getHeight(),
                    Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(connectedIcon);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(Color.parseColor("#f5f5f5"));
            canvas.drawCircle(icon.getWidth() / 2, icon.getHeight() / 2, icon.getWidth() / 2, paint);
            paint.setColorFilter(
                    new PorterDuffColorFilter(SIAApp.SIA_APP.school.getColor(), PorterDuff.Mode.SRC_ATOP));
            canvas.drawBitmap(icon, null, new RectF(icon.getHeight() / 4.0f, icon.getHeight() / 4.0f,
                    icon.getHeight() - icon.getHeight() / 4.0f, icon.getHeight() - icon.getHeight() / 4.0f),
                    paint);

            Intent newTaskIntent = new Intent(this, MainActivity.class);
            newTaskIntent.setAction(Intent.ACTION_MAIN);
            newTaskIntent.putExtra("fragment", fragments.get(i).type.toString());

            ShortcutInfo shortcut = new ShortcutInfo.Builder(this, fragments.get(i).name)
                    .setShortLabel(fragments.get(i).name).setLongLabel(fragments.get(i).name)
                    .setIcon(Icon.createWithBitmap(connectedIcon)).setIntent(newTaskIntent).build();

            shortcutManager.addDynamicShortcuts(Arrays.asList(shortcut));
        }
    }

    if (SIAApp.SIA_APP.preferences.getBoolean("app_130_upgrade", true)) {
        if (!SIAApp.SIA_APP.preferences.getBoolean("first_use_filter", true)) {
            TextDialog.newInstance(R.string.upgrade1_3title, R.string.upgrade1_3)
                    .show(getSupportFragmentManager(), "upgrade_dialog");
        }

        SIAApp.SIA_APP.preferences.edit().putBoolean("app_130_upgrade", false).apply();
    }

    snowView = (SnowView) findViewById(R.id.snow_view);

    shareToolbar = (Toolbar) findViewById(R.id.share_toolbar);
    shareToolbar.getMenu().clear();
    shareToolbar.inflateMenu(R.menu.share_toolbar_menu);
    shareToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleShareToolbar(false);
            for (Shareable s : MainActivity.this.shared) {
                s.setMarked(false);
            }
            MainActivity.this.shared.clear();

            mContent.updateFragment();
        }
    });

    shareToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            toggleShareToolbar(false);

            HashMap<Date, ArrayList<Shareable>> dates = new HashMap<Date, ArrayList<Shareable>>();

            for (Shareable s : MainActivity.this.shared) {
                ArrayList<Shareable> list = dates.get(s.getDate());
                if (list == null) {
                    list = new ArrayList<Shareable>();
                    dates.put(s.getDate(), list);
                }

                list.add(s);

                s.setMarked(false);
            }
            MainActivity.this.shared.clear();

            List<Date> dateList = new ArrayList<Date>(dates.keySet());
            Collections.sort(dateList);
            String content = "";

            for (Date key : dateList) {
                content += SubstListAdapter.translateDay(key) + "\n\n";

                Collections.sort(dates.get(key));
                for (Shareable s : dates.get(key)) {
                    content += s.getShareContent() + "\n";
                }

                content += "\n";
            }

            content = content.substring(0, content.length() - 1);

            mContent.updateFragment();

            if (item.getItemId() == R.id.action_copy) {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

                ClipData clip = ClipData.newPlainText(getString(R.string.entries), content);
                clipboard.setPrimaryClip(clip);
            } else if (item.getItemId() == R.id.action_share) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, content);
                sendIntent.setType("text/plain");
                startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
            }

            return true;
        }
    });

    if (shared.size() > 0) {
        shareToolbar.setVisibility(View.VISIBLE);
        updateShareToolbarText();
    }

    // if a fragment is opened via a notification or a shortcut reset the shared entries
    // delete extra fragment because the same intent is used when the device gets rotated and the user could have opened a new fragment
    if (intent != null && intent.hasExtra("fragment")) {
        resetShareToolbar();
        intent.removeExtra("fragment");
    }

}