Example usage for android.content.res Resources getDisplayMetrics

List of usage examples for android.content.res Resources getDisplayMetrics

Introduction

In this page you can find the example usage for android.content.res Resources getDisplayMetrics.

Prototype

public DisplayMetrics getDisplayMetrics() 

Source Link

Document

Return the current display metrics that are in effect for this resource object.

Usage

From source file:de.cachebox_test.splash.java

private void Initial(int width, int height) {
    // Jetzt ist der workPath erstmal festgelegt.
    Log.debug(log, "Initial()");

    // lolipop ask write permission
    if (android.os.Build.VERSION.SDK_INT > 20) {
        // if (LolipopworkPath != null) workPath = LolipopworkPath + "/cachebox";
    }/*from w  w w .  j  a v  a2  s  . co  m*/

    // Zur Kompatibilitt mit lteren Installationen wird hier noch die redirection.txt abgefragt
    if (FileIO.FileExists(workPath + "/redirection.txt")) {
        BufferedReader Filereader;

        try {
            Filereader = new BufferedReader(new FileReader(workPath + "/redirection.txt"));
            String line;

            while ((line = Filereader.readLine()) != null) {
                // chk ob der umleitungs Ordner existiert
                if (FileIO.FileExists(line)) {
                    workPath = line;
                }
            }

            Filereader.close();
        } catch (IOException e) {
            Log.err(log, "read redirection", e);
        }

    }

    new Config(workPath);

    // Read Config
    Config.Initialize(workPath, workPath + "/cachebox.config");

    // hier muss die Config Db initialisiert werden
    Database.Settings = new AndroidDB(DatabaseType.Settings, this);

    boolean userFolderExists = FileIO.createDirectory(Config.mWorkPath + "/User");

    if (!userFolderExists)
        return;
    Database.Settings.StartUp(Config.mWorkPath + "/User/Config.db3");

    // initialisieren der PlattformSettings
    PlatformSettings.setPlatformSettings(new IPlatformSettings() {

        @Override
        public void Write(SettingBase<?> setting) {
            if (androidSetting == null)
                androidSetting = splash.this.getSharedPreferences(Global.PREFS_NAME, 0);
            if (androidSettingEditor == null)
                androidSettingEditor = androidSetting.edit();

            if (setting instanceof SettingBool) {
                androidSettingEditor.putBoolean(setting.getName(), ((SettingBool) setting).getValue());
            } else if (setting instanceof SettingString) {
                androidSettingEditor.putString(setting.getName(), ((SettingString) setting).getValue());
            } else if (setting instanceof SettingInt) {
                androidSettingEditor.putInt(setting.getName(), ((SettingInt) setting).getValue());
            }

            // Commit the edits!
            androidSettingEditor.commit();
        }

        @Override
        public SettingBase<?> Read(SettingBase<?> setting) {
            if (androidSetting == null)
                androidSetting = splash.this.getSharedPreferences(Global.PREFS_NAME, 0);

            if (setting instanceof SettingString) {
                String value = androidSetting.getString(setting.getName(), "");
                ((SettingString) setting).setValue(value);
            } else if (setting instanceof SettingBool) {
                boolean value = androidSetting.getBoolean(setting.getName(),
                        ((SettingBool) setting).getDefaultValue());
                ((SettingBool) setting).setValue(value);
            } else if (setting instanceof SettingInt) {
                int value = androidSetting.getInt(setting.getName(), ((SettingInt) setting).getDefaultValue());
                ((SettingInt) setting).setValue(value);
            }
            setting.clearDirty();
            return setting;
        }
    });

    // wenn die Settings DB neu Erstellt wurde, mssen die Default werte
    // geschrieben werden.
    if (Database.Settings.isDbNew()) {
        Config.settings.LoadAllDefaultValues();
        Config.settings.WriteToDB();
    } else {
        Config.settings.ReadFromDB();
    }

    // Add Android Only Settings
    AndroidSettings.addToSettiongsList();

    new CB_SLF4J(workPath);
    CB_SLF4J.setLogLevel((LogLevel) Config.AktLogLevel.getEnumValue());
    Config.AktLogLevel.addChangedEventListener(new IChanged() {
        @Override
        public void isChanged() {
            CB_SLF4J.setLogLevel((LogLevel) Config.AktLogLevel.getEnumValue());
        }
    });

    if (GlobalCore.isTab) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Log.debug(log, "setRequestedOrientation SCREEN_ORIENTATION_LANDSCAPE");
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Log.debug(log, "setRequestedOrientation SCREEN_ORIENTATION_PORTRAIT");
    }

    Database.Data = new AndroidDB(DatabaseType.CacheBox, this);

    // copy AssetFolder only if Rev-Number changed, like at new installation
    try {
        if (Config.installRev.getValue() < GlobalCore.CurrentRevision) {
            String[] exclude = new String[] { "webkit", "sound", "sounds", "images", "skins", "lang",
                    "kioskmode", "string-files", "" };
            copyAssetFolder myCopie = new copyAssetFolder();

            myCopie.copyAll(getAssets(), Config.mWorkPath, exclude);
            Config.installRev.setValue(GlobalCore.CurrentRevision);
            Config.newInstall.setValue(true);
            Config.AcceptChanges();

            File CreateFile;

            // create .nomedia Files
            try {
                CreateFile = FileFactory.createFile(workPath + "/data/.nomedia");
                CreateFile.getParentFile().mkdirs();
                CreateFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                CreateFile = FileFactory.createFile(workPath + "/skins/.nomedia");
                CreateFile.getParentFile().mkdirs();
                CreateFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                CreateFile = FileFactory.createFile(workPath + "/repository/.nomedia");
                CreateFile.getParentFile().mkdirs();
                CreateFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                CreateFile = FileFactory.createFile(workPath + "/Repositories/.nomedia");
                CreateFile.getParentFile().mkdirs();
                CreateFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                CreateFile = FileFactory.createFile(workPath + "/cache/.nomedia");
                CreateFile.getParentFile().mkdirs();
                CreateFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            Config.newInstall.setValue(false);
        }
    } catch (Exception e) {
        Log.err(log, "Copy Asset", e);
    }

    // save askAgain for show SandboxMsg
    Config.showSandbox.setValue(showSandbox);
    Config.AcceptChanges();

    // UiSize Structur fr die Berechnung der Gren zusammen stellen!

    Log.debug(log, GlobalCore.getVersionString());
    Log.debug(log, "Screen width/height:" + width + "/" + height);

    if (ui == null) {
        Resources res = splash.this.getResources();

        Log.debug(log, "create new devices-sizes");
        ui = new DevicesSizes();

        ui.Window = new Size(width, height);
        ui.Density = res.getDisplayMetrics().density;
        ui.isLandscape = false;

        // Log Size values
        Log.debug(log, "UI-Sizes");
        Log.debug(log, "ui.Window: " + ui.Window.toString());
        Log.debug(log, "ui.Density: " + ui.Density);
        Log.debug(log, "ui.isLandscape: " + ui.isLandscape);

    }

    new UiSizes();
    UI_Size_Base.that.initial(ui);
    GL_UISizes.defaultDPI = ui.Density;

    Global.Paints.init(this);

    {// restrict MapsforgeScaleFactor to max 1.0f (TileSize 256x256)
        ext_AndroidGraphicFactory.createInstance(this.getApplication());

        float restrictedScaleFactor = 1f;
        DisplayModel.setDeviceScaleFactor(restrictedScaleFactor);
        new de.cachebox_test.Map.AndroidManager(new DisplayModel());
    }

    Initial2();
}

From source file:com.android.launcher3.allapps.AllAppsGridAdapter.java

public AllAppsGridAdapter(Launcher launcher, AlphabeticalAppsList apps, View.OnTouchListener touchListener,
        View.OnClickListener iconClickListener, View.OnLongClickListener iconLongClickListener) {
    Resources res = launcher.getResources();
    mLauncher = launcher;//from  w w  w  .  j a  v a 2s  . com
    mApps = apps;
    mEmptySearchMessage = res.getString(R.string.all_apps_loading_message);
    mGridSizer = new GridSpanSizer();
    mGridLayoutMgr = new AppsGridLayoutManager(launcher);
    mGridLayoutMgr.setSpanSizeLookup(mGridSizer);
    mItemDecoration = new GridItemDecoration();
    mLayoutInflater = LayoutInflater.from(launcher);
    mTouchListener = touchListener;
    mIconClickListener = iconClickListener;
    mIconLongClickListener = iconLongClickListener;
    mSectionNamesMargin = res.getDimensionPixelSize(R.dimen.all_apps_grid_view_start_margin);
    mSectionHeaderOffset = res.getDimensionPixelSize(R.dimen.all_apps_grid_section_y_offset);
    mIsRtl = Utilities.isRtl(res);

    mSectionTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mSectionTextPaint.setTextSize(res.getDimensionPixelSize(R.dimen.all_apps_grid_section_text_size));
    mSectionTextPaint.setColor(res.getColor(R.color.all_apps_grid_section_text_color));

    mPredictedAppsDividerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPredictedAppsDividerPaint.setStrokeWidth(Utilities.pxFromDp(1f, res.getDisplayMetrics()));
    mPredictedAppsDividerPaint.setColor(0x1E000000);
    mPredictionBarDividerOffset = (-res.getDimensionPixelSize(R.dimen.all_apps_prediction_icon_bottom_padding)
            + res.getDimensionPixelSize(R.dimen.all_apps_icon_top_bottom_padding)) / 2;
}

From source file:com.hippo.vector.VectorDrawable.java

void updateDimensionInfo(@Nullable Resources res, boolean updateConstantStateDensity) {
    if (res != null) {
        final int densityDpi = res.getDisplayMetrics().densityDpi;
        final int targetDensity = densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi;

        if (updateConstantStateDensity) {
            mVectorState.mVPathRenderer.mTargetDensity = targetDensity;
        } else {/*from www .ja v  a 2  s  . com*/
            final int constantStateDensity = mVectorState.mVPathRenderer.mTargetDensity;
            if (targetDensity != constantStateDensity && constantStateDensity != 0) {
                mDpiScaledWidth = Utils.scaleFromDensity((int) mVectorState.mVPathRenderer.mBaseWidth,
                        constantStateDensity, targetDensity);
                mDpiScaledHeight = Utils.scaleFromDensity((int) mVectorState.mVPathRenderer.mBaseHeight,
                        constantStateDensity, targetDensity);
                final int left = Utils.scaleFromDensity(mVectorState.mVPathRenderer.mOpticalInsets.left,
                        constantStateDensity, targetDensity);
                final int right = Utils.scaleFromDensity(mVectorState.mVPathRenderer.mOpticalInsets.right,
                        constantStateDensity, targetDensity);
                final int top = Utils.scaleFromDensity(mVectorState.mVPathRenderer.mOpticalInsets.top,
                        constantStateDensity, targetDensity);
                final int bottom = Utils.scaleFromDensity(mVectorState.mVPathRenderer.mOpticalInsets.bottom,
                        constantStateDensity, targetDensity);
                mDpiScaleInsets = Insets.of(left, top, right, bottom);
                return;
            }
        }
    }
    // For all the other cases, like either res is null, constant state is not initialized or
    // target density is the same as the constant state, we will just use the constant state
    // dimensions.
    mDpiScaledWidth = (int) mVectorState.mVPathRenderer.mBaseWidth;
    mDpiScaledHeight = (int) mVectorState.mVPathRenderer.mBaseHeight;
    mDpiScaleInsets = mVectorState.mVPathRenderer.mOpticalInsets;
}

From source file:de.cachebox_test.splash.java

@SuppressWarnings("deprecation")
@Override/*from  ww w .j av a 2 s. c  om*/
protected void onStart() {
    super.onStart();
    Log.debug(log, "onStart");

    if (android.os.Build.VERSION.SDK_INT >= 23) {
        PermissionCheck.checkNeededPermissions(this);
    }

    // initial GDX
    Gdx.files = new AndroidFiles(this.getAssets(), this.getFilesDir().getAbsolutePath());
    // first, try to find stored preferences of workPath
    androidSetting = this.getSharedPreferences(Global.PREFS_NAME, 0);

    workPath = androidSetting.getString("WorkPath", Environment.getDataDirectory() + "/cachebox");
    boolean askAgain = androidSetting.getBoolean("AskAgain", true);
    showSandbox = androidSetting.getBoolean("showSandbox", false);

    Global.initTheme(this);
    Global.InitIcons(this);

    CB_Android_FileExplorer fileExplorer = new CB_Android_FileExplorer(this);
    PlatformConnector.setGetFileListener(fileExplorer);
    PlatformConnector.setGetFolderListener(fileExplorer);

    String LangPath = androidSetting.getString("Sel_LanguagePath", "");
    if (LangPath.length() == 0) {
        // set default lang

        String locale = Locale.getDefault().getLanguage();
        if (locale.contains("de")) {
            LangPath = "data/lang/de/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("cs")) {
            LangPath = "data/lang/cs/strings.ini";
        } else if (locale.contains("fr")) {
            LangPath = "data/lang/fr/strings.ini";
        } else if (locale.contains("nl")) {
            LangPath = "data/lang/nl/strings.ini";
        } else if (locale.contains("pl")) {
            LangPath = "data/lang/pl/strings.ini";
        } else if (locale.contains("pt")) {
            LangPath = "data/lang/pt/strings.ini";
        } else if (locale.contains("hu")) {
            LangPath = "data/lang/hu/strings.ini";
        } else {
            LangPath = "data/lang/en-GB/strings.ini";
        }
    }

    new Translation(workPath, FileType.Internal);
    try {
        Translation.LoadTranslation(LangPath);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // check Write permission
    if (!askAgain) {
        if (!FileIO.checkWritePermission(workPath)) {
            askAgain = true;
            if (!ToastEx) {
                ToastEx = true;
                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
            }
        }
    }

    if ((askAgain)) {
        // no saved workPath found -> search sd-cards and if more than 1 is found give the user the possibility to select one

        String externalSd = getExternalSdPath("/CacheBox");

        boolean hasExtSd;
        final String externalSd2 = externalSd;

        if (externalSd != null) {
            hasExtSd = (externalSd.length() > 0) && (!externalSd.equalsIgnoreCase(workPath));
        } else {
            hasExtSd = false;
        }

        // externe SD wurde gefunden != internal
        // oder Tablet Layout mglich
        // -> Auswahldialog anzeigen
        try {
            final Dialog dialog = new Dialog(context) {
                @Override
                public boolean onKeyDown(int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        splash.this.finish();
                    }
                    return super.onKeyDown(keyCode, event);
                }
            };

            dialog.setContentView(R.layout.sdselectdialog);
            TextView title = (TextView) dialog.findViewById(R.id.select_sd_title);
            title.setText(Translation.Get("selectWorkSpace") + "\n\n");
            /*
             * TextView tbLayout = (TextView) dialog.findViewById(R.id.select_sd_layout); tbLayout.setText("\nLayout"); final RadioGroup
             * rgLayout = (RadioGroup) dialog.findViewById(R.id.select_sd_radiogroup); final RadioButton rbHandyLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_handylayout); final RadioButton rbTabletLayout = (RadioButton)
             * dialog.findViewById(R.id.select_sd_tabletlayout); rbHandyLayout.setText("Handy-Layout");
             * rbTabletLayout.setText("Tablet-Layout"); if (!GlobalCore.posibleTabletLayout) {
             * rgLayout.setVisibility(RadioGroup.INVISIBLE); rbHandyLayout.setChecked(true); } else { if (GlobalCore.isTab) {
             * rbTabletLayout.setChecked(true); } else { rbHandyLayout.setChecked(true); } }
             */
            final CheckBox cbAskAgain = (CheckBox) dialog.findViewById(R.id.select_sd_askagain);
            cbAskAgain.setText(Translation.Get("AskAgain"));
            cbAskAgain.setChecked(askAgain);
            Button buttonI = (Button) dialog.findViewById(R.id.button1);
            buttonI.setText("Internal SD\n\n" + workPath);
            buttonI.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();

                    // show please wait dialog
                    showPleaseWaitDialog();

                    // use internal SD -> nothing to change
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            boolean askAgain = cbAskAgain.isChecked();
                            // boolean useTabletLayout = rbTabletLayout.isChecked();
                            saveWorkPath(askAgain/* , useTabletLayout */);
                            dialog.dismiss();
                            startInitial();
                        }
                    };
                    thread.start();
                }
            });
            Button buttonE = (Button) dialog.findViewById(R.id.button2);
            final boolean isSandbox = externalSd == null ? false
                    : externalSd.contains("Android/data/de.cachebox_test");
            if (!hasExtSd) {
                buttonE.setVisibility(Button.INVISIBLE);
            } else {
                String extSdText = isSandbox ? "External SD SandBox\n\n" : "External SD\n\n";
                buttonE.setText(extSdText + externalSd);
            }

            buttonE.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // show KitKat Massage?

                    if (isSandbox && !showSandbox) {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

                        // set title
                        alertDialogBuilder.setTitle("KitKat Sandbox");

                        // set dialog message
                        alertDialogBuilder.setMessage(Translation.Get("Desc_Sandbox")).setCancelable(false)
                                .setPositiveButton(Translation.Get("yes"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, run Sandbox Path

                                                showSandbox = true;
                                                Config.AcceptChanges();

                                                // close select dialog
                                                dialog.dismiss();

                                                // show please wait dialog
                                                showPleaseWaitDialog();

                                                // use external SD -> change workPath
                                                Thread thread = new Thread() {
                                                    @Override
                                                    public void run() {
                                                        workPath = externalSd2;
                                                        boolean askAgain = cbAskAgain.isChecked();
                                                        // boolean useTabletLayout = rbTabletLayout.isChecked();
                                                        saveWorkPath(askAgain/* , useTabletLayout */);
                                                        startInitial();
                                                    }
                                                };
                                                thread.start();
                                            }
                                        })
                                .setNegativeButton(Translation.Get("no"),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int id) {
                                                // if this button is clicked, just close
                                                // the dialog box and do nothing
                                                dialog.cancel();
                                            }
                                        });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();
                    } else {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = externalSd2;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();
                    }
                }
            });

            LinearLayout ll = (LinearLayout) dialog.findViewById(R.id.scrollViewLinearLayout);

            // add all Buttons for created Workspaces

            AdditionalWorkPathArray = getAdditionalWorkPathArray();

            for (final String AddWorkPath : AdditionalWorkPathArray) {

                final String Name = FileIO.GetFileNameWithoutExtension(AddWorkPath);

                if (!FileIO.checkWritePermission(AddWorkPath)) {
                    // delete this Work Path
                    deleteWorkPath(AddWorkPath);
                    continue;
                }

                Button buttonW = new Button(context);
                buttonW.setText(Name + "\n\n" + AddWorkPath);

                buttonW.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {

                        // setting the MassageBox then the UI_sizes are not initial in this moment
                        Resources res = splash.this.getResources();
                        float scale = res.getDisplayMetrics().density;
                        float calcBase = 533.333f * scale;

                        FrameLayout frame = (FrameLayout) findViewById(R.id.frameLayout1);
                        int width = frame.getMeasuredWidth();
                        int height = frame.getMeasuredHeight();

                        MessageBox.Builder.WindowWidth = width;
                        MessageBox.Builder.WindowHeight = height;
                        MessageBox.Builder.textSize = (calcBase
                                / res.getDimensionPixelSize(R.dimen.BtnTextSize)) * scale;
                        MessageBox.Builder.ButtonHeight = (int) (50 * scale);

                        // Ask before delete
                        msg = (MessageBox) MessageBox.Show(Translation.Get("shuredeleteWorkspace", Name),
                                Translation.Get("deleteWorkspace"), MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (which == MessageBox.BUTTON_POSITIVE) {
                                            // Delete this Workpath only from Settings don't delete any File
                                            deleteWorkPath(AddWorkPath);
                                        }
                                        // Start again to exclude the old Folder
                                        msg.dismiss();
                                        onStart();
                                    }

                                });

                        dialog.dismiss();
                        return true;
                    }
                });

                buttonW.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // close select dialog
                        dialog.dismiss();

                        // show please wait dialog
                        showPleaseWaitDialog();

                        // use external SD -> change workPath
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                workPath = AddWorkPath;
                                boolean askAgain = cbAskAgain.isChecked();
                                // boolean useTabletLayout = rbTabletLayout.isChecked();
                                saveWorkPath(askAgain/* , useTabletLayout */);
                                startInitial();
                            }
                        };
                        thread.start();

                    }
                });

                ll.addView(buttonW);
            }

            Button buttonC = (Button) dialog.findViewById(R.id.buttonCreateWorkspace);
            buttonC.setText(Translation.Get("createWorkSpace"));
            buttonC.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // close select dialog
                    dialog.dismiss();
                    getFolderReturnListener = new IgetFolderReturnListener() {

                        @Override
                        public void getFolderReturn(String Path) {
                            if (FileIO.checkWritePermission(Path)) {

                                AdditionalWorkPathArray.add(Path);
                                writeAdditionalWorkPathArray(AdditionalWorkPathArray);
                                // Start again to include the new Folder
                                onStart();
                            } else {
                                String WriteProtectionMsg = Translation.Get("NoWriteAcces");
                                Toast.makeText(splash.this, WriteProtectionMsg, Toast.LENGTH_LONG).show();
                            }
                        }
                    };

                    PlatformConnector.getFolder("", Translation.Get("select_folder"), Translation.Get("select"),
                            getFolderReturnListener);

                }
            });

            dialog.show();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else {
        if (GlobalCore.displayType == DisplayType.Large || GlobalCore.displayType == DisplayType.xLarge)
            GlobalCore.isTab = isLandscape;

        // restore the saved workPath
        // test whether workPath is available by checking the free size on the SD
        String workPathToTest = workPath.substring(0, workPath.lastIndexOf("/"));
        long bytesAvailable = 0;
        try {
            StatFs stat = new StatFs(workPathToTest);
            bytesAvailable = (long) stat.getBlockSize() * (long) stat.getBlockCount();
        } catch (Exception ex) {
            bytesAvailable = 0;
        }
        if (bytesAvailable == 0) {
            // there is a workPath stored but this workPath is not available at the moment (maybe SD is removed)
            Toast.makeText(splashActivity,
                    "WorkPath " + workPath + " is not available!\nMaybe SD-Card is removed?", Toast.LENGTH_LONG)
                    .show();
            finish();
            return;
        }

        startInitial();
    }

}

From source file:org.akop.crosswords.view.CrosswordView.java

public CrosswordView(Context context, AttributeSet attrs) {
    super(context, attrs);

    if (!isInEditMode()) {
        setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }//from  ww w.  j a v a  2 s.c  om

    // Set drawing defaults
    Resources r = context.getResources();
    DisplayMetrics dm = r.getDisplayMetrics();

    int cellFillColor = NORMAL_CELL_FILL_COLOR;
    int cheatedCellFillColor = CHEATED_CELL_FILL_COLOR;
    int mistakeCellFillColor = MISTAKE_CELL_FILL_COLOR;
    int selectedWordFillColor = SELECTED_WORD_FILL_COLOR;
    int selectedCellFillColor = SELECTED_CELL_FILL_COLOR;
    int textColor = TEXT_COLOR;
    int cellStrokeColor = CELL_STROKE_COLOR;
    int circleStrokeColor = CIRCLE_STROKE_COLOR;

    float numberTextSize = NUMBER_TEXT_SIZE * dm.scaledDensity;
    float answerTextSize = ANSWER_TEXT_SIZE * dm.scaledDensity;

    mCellSize = CELL_SIZE * dm.density;
    mNumberTextPadding = NUMBER_TEXT_PADDING * dm.density;
    mAnswerTextPadding = ANSWER_TEXT_PADDING * dm.density;

    // Read supplied attributes
    if (attrs != null) {
        Resources.Theme theme = context.getTheme();
        TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.Crossword, 0, 0);
        mCellSize = a.getDimension(R.styleable.Crossword_cellSize, mCellSize);
        mNumberTextPadding = a.getDimension(R.styleable.Crossword_numberTextPadding, mNumberTextPadding);
        numberTextSize = a.getDimension(R.styleable.Crossword_numberTextSize, numberTextSize);
        mAnswerTextPadding = a.getDimension(R.styleable.Crossword_answerTextPadding, mAnswerTextPadding);
        answerTextSize = a.getDimension(R.styleable.Crossword_answerTextSize, answerTextSize);
        cellFillColor = a.getColor(R.styleable.Crossword_defaultCellFillColor, cellFillColor);
        cheatedCellFillColor = a.getColor(R.styleable.Crossword_cheatedCellFillColor, cheatedCellFillColor);
        mistakeCellFillColor = a.getColor(R.styleable.Crossword_mistakeCellFillColor, mistakeCellFillColor);
        selectedWordFillColor = a.getColor(R.styleable.Crossword_selectedWordFillColor, selectedWordFillColor);
        selectedCellFillColor = a.getColor(R.styleable.Crossword_selectedCellFillColor, selectedCellFillColor);
        cellStrokeColor = a.getColor(R.styleable.Crossword_cellStrokeColor, cellStrokeColor);
        circleStrokeColor = a.getColor(R.styleable.Crossword_circleStrokeColor, circleStrokeColor);
        textColor = a.getColor(R.styleable.Crossword_textColor, textColor);
        a.recycle();
    }

    mMarkerSideLength = mCellSize * MARKER_TRIANGLE_LENGTH_FRACTION;

    // Init paints
    mCellFillPaint = new Paint();
    mCellFillPaint.setColor(cellFillColor);
    mCellFillPaint.setStyle(Paint.Style.FILL);

    mCheatedCellFillPaint = new Paint();
    mCheatedCellFillPaint.setColor(cheatedCellFillColor);
    mCheatedCellFillPaint.setStyle(Paint.Style.FILL);

    mMistakeCellFillPaint = new Paint();
    mMistakeCellFillPaint.setColor(mistakeCellFillColor);
    mMistakeCellFillPaint.setStyle(Paint.Style.FILL);

    mSelectedWordFillPaint = new Paint();
    mSelectedWordFillPaint.setColor(selectedWordFillColor);
    mSelectedWordFillPaint.setStyle(Paint.Style.FILL);

    mSelectedCellFillPaint = new Paint();
    mSelectedCellFillPaint.setColor(selectedCellFillColor);
    mSelectedCellFillPaint.setStyle(Paint.Style.FILL);

    mCellStrokePaint = new Paint();
    mCellStrokePaint.setColor(cellStrokeColor);
    mCellStrokePaint.setStyle(Paint.Style.STROKE);
    //      mCellStrokePaint.setStrokeWidth(1);

    mCircleStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mCircleStrokePaint.setColor(circleStrokeColor);
    mCircleStrokePaint.setStyle(Paint.Style.STROKE);
    mCircleStrokePaint.setStrokeWidth(1);

    mNumberTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mNumberTextPaint.setColor(textColor);
    mNumberTextPaint.setTextAlign(Paint.Align.CENTER);
    mNumberTextPaint.setTextSize(numberTextSize);

    mNumberStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mNumberStrokePaint.setColor(cellFillColor);
    mNumberStrokePaint.setTextAlign(Paint.Align.CENTER);
    mNumberStrokePaint.setTextSize(numberTextSize);
    mNumberStrokePaint.setStyle(Paint.Style.STROKE);
    mNumberStrokePaint.setStrokeWidth(NUMBER_TEXT_STROKE_WIDTH * dm.scaledDensity);

    mAnswerTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mAnswerTextPaint.setColor(textColor);
    mAnswerTextPaint.setTextSize(answerTextSize);
    mAnswerTextPaint.setTextAlign(Paint.Align.CENTER);

    // http://www.google.com/fonts/specimen/Kalam
    Typeface typeface = Typeface.createFromAsset(context.getAssets(), "kalam-regular.ttf");
    mAnswerTextPaint.setTypeface(typeface);

    // Init rest of the values
    mCircleRadius = (mCellSize / 2) - mCircleStrokePaint.getStrokeWidth();
    mPuzzleCells = EMPTY_CELLS;
    mPuzzleWidth = 0;
    mPuzzleHeight = 0;
    mAllowedChars = EMPTY_CHARS;

    mRenderScale = 0;
    mBitmapOffset = new PointF();
    mCenteredOffset = new PointF();
    mTranslationBounds = new RectF();

    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
    mGestureDetector = new GestureDetector(context, new GestureListener());

    mContentRect = new RectF();
    mPuzzleRect = new RectF();

    mBitmapPaint = new Paint(Paint.FILTER_BITMAP_FLAG);

    mScroller = new Scroller(context, null, true);
    mZoomer = new Zoomer(context);

    setFocusableInTouchMode(true);
    setOnKeyListener(this);
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java

private void reloadSwipeThresholdsSettings(final Resources res) {
    final float density = res.getDisplayMetrics().density;
    mSwipeVelocityThreshold = (int) (AnyApplication.getConfig().getSwipeVelocityThreshold() * density);
    mSwipeXDistanceThreshold = (int) (AnyApplication.getConfig().getSwipeDistanceThreshold() * density);
    Keyboard kbd = getKeyboard();/*from w w  w  . j  ava2s .c o  m*/
    if (kbd != null) {
        mSwipeYDistanceThreshold = (int) (mSwipeXDistanceThreshold
                * (((float) kbd.getHeight()) / ((float) getWidth())));
    } else {
        mSwipeYDistanceThreshold = 0;
    }
    //In case we don't have a Y distance, we'll use X's
    if (mSwipeYDistanceThreshold == 0) //noinspection SuspiciousNameCombination
        mSwipeYDistanceThreshold = mSwipeXDistanceThreshold;

    mSwipeSpaceXDistanceThreshold = mSwipeXDistanceThreshold / 2;
    mSwipeYDistanceThreshold = mSwipeYDistanceThreshold / 2;

    mScrollXDistanceThreshold = mSwipeXDistanceThreshold / 8;
    mScrollYDistanceThreshold = mSwipeYDistanceThreshold / 8;
}

From source file:dheeraj.sachan.advancedandroidshit.test.CustomActionMenuPresenter.java

@Override
public void initForMenu(Context context, MenuBuilder menu) {
    super.initForMenu(context, menu);

    final Resources res = context.getResources();

    final ActionBarPolicy abp = ActionBarPolicy.get(context);
    if (!mReserveOverflowSet) {
        mReserveOverflow = abp.showsOverflowMenuButton();
    }/* ww w. j  a v a  2 s  .c o  m*/

    if (!mWidthLimitSet) {
        mWidthLimit = abp.getEmbeddedMenuWidthLimit();
    }

    // Measure for initial configuration
    if (!mMaxItemsSet) {
        mMaxItems = abp.getMaxActionButtons();
    }

    int width = mWidthLimit;
    if (mReserveOverflow) {
        if (mOverflowButton == null) {
            mOverflowButton = new OverflowMenuButton(mSystemContext);
            if (mPendingOverflowIconSet) {
                mOverflowButton.setImageDrawable(mPendingOverflowIcon);
                mPendingOverflowIcon = null;
                mPendingOverflowIconSet = false;
            }
            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            mOverflowButton.measure(spec, spec);
        }
        width -= mOverflowButton.getMeasuredWidth();
    } else {
        mOverflowButton = null;
    }

    mActionItemWidthLimit = width;

    mMinCellSize = (int) (MIN_CELL_SIZE * res.getDisplayMetrics().density);

    // Drop a scrap view as it may no longer reflect the proper context/config.
    mScrapActionButtonView = null;
}

From source file:android.support.v7ox.widget.ActionMenuPresenter.java

@Override
public void initForMenu(Context context, MenuBuilder menu) {
    super.initForMenu(context, menu);

    final Resources res = context.getResources();

    final ActionBarPolicy abp = ActionBarPolicy.get(context);
    if (!mReserveOverflowSet) {
        mReserveOverflow = abp.showsOverflowMenuButton();
    }/*from ww  w .ja  v  a 2  s .  c  o  m*/

    if (!mWidthLimitSet) {
        mWidthLimit = abp.getEmbeddedMenuWidthLimit();
    }

    // Measure for initial configuration
    if (!mMaxItemsSet) {
        mMaxItems = abp.getMaxActionButtons();
    }

    int width = mWidthLimit;
    if (mReserveOverflow) {
        if (mOverflowButton == null) {
            mOverflowButton = new OverflowMenuButton(mSystemContext);
            if (mPendingOverflowIconSet) {
                mOverflowButton.setImageDrawable(mPendingOverflowIcon);
                mPendingOverflowIcon = null;
                mPendingOverflowIconSet = false;
            }
            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            mOverflowButton.measure(spec, spec);
        }
        width -= mOverflowButton.getMeasuredWidth();
    } else {
        mOverflowButton = null;
    }

    mActionItemWidthLimit = width;

    mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density);

    // Drop a scrap view as it may no longer reflect the proper context/config.
    mScrapActionButtonView = null;
}

From source file:com.xandy.calendar.AllInOneActivity.java

@Override
protected void onCreate(Bundle icicle) {
    if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) {
        setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
    }/*from  ww w.j  av  a  2  s.  c om*/
    super.onCreate(icicle);

    if (icicle != null && icicle.containsKey(BUNDLE_KEY_CHECK_ACCOUNTS)) {
        mCheckForAccounts = icicle.getBoolean(BUNDLE_KEY_CHECK_ACCOUNTS);
    }
    // Launch add google account if this is first time and there are no
    // accounts yet
    if (mCheckForAccounts && !Utils.getSharedPreference(this, GeneralPreferences.KEY_SKIP_SETUP, false)) {

        mHandler = new QueryHandler(this.getContentResolver());
        mHandler.startQuery(0, null, Calendars.CONTENT_URI, new String[] { Calendars._ID }, null,
                null /* selection args */, null /* sort order */);
    }

    // This needs to be created before setContentView
    mController = CalendarController.getInstance(this);

    // Get time from intent or icicle
    long timeMillis = -1;
    int viewType = -1;
    final Intent intent = getIntent();
    if (icicle != null) {
        timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
        viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1);
    } else {
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            // Open EventInfo later
            timeMillis = parseViewAction(intent);
        }

        if (timeMillis == -1) {
            timeMillis = Utils.timeFromIntentInMillis(intent);
        }
    }

    if (viewType == -1 || viewType > ViewType.MAX_VALUE) {
        viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
    }
    mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
    Time t = new Time(mTimeZone);
    t.set(timeMillis);

    if (DEBUG) {
        if (icicle != null && intent != null) {
            Log.d(TAG, "both, icicle:" + icicle.toString() + "  intent:" + intent.toString());
        } else {
            Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
        }
    }

    Resources res = getResources();
    mHideString = res.getString(R.string.hide_controls);
    mShowString = res.getString(R.string.show_controls);
    mOrientation = res.getConfiguration().orientation;
    if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        mControlsAnimateWidth = (int) res.getDimension(R.dimen.calendar_controls_width);
        if (mControlsParams == null) {
            mControlsParams = new LayoutParams(mControlsAnimateWidth, 0);
        }
        mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    } else {
        // Make sure width is in between allowed min and max width values
        mControlsAnimateWidth = Math.max(res.getDisplayMetrics().widthPixels * 45 / 100,
                (int) res.getDimension(R.dimen.min_portrait_calendar_controls_width));
        mControlsAnimateWidth = Math.min(mControlsAnimateWidth,
                (int) res.getDimension(R.dimen.max_portrait_calendar_controls_width));
    }

    mControlsAnimateHeight = (int) res.getDimension(R.dimen.calendar_controls_height);

    mHideControls = !Utils.getSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, true);
    mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config);
    mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config);
    mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month);
    mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls);
    mShowEventDetailsWithAgenda = Utils.getConfigBool(this, R.bool.show_event_details_with_agenda);
    mShowEventInfoFullScreenAgenda = Utils.getConfigBool(this, R.bool.agenda_show_event_info_full_screen);
    mShowEventInfoFullScreen = Utils.getConfigBool(this, R.bool.show_event_info_full_screen);
    mCalendarControlsAnimationTime = res.getInteger(R.integer.calendar_controls_animation_time);
    Utils.setAllowWeekForDetailView(mIsMultipane);

    // setContentView must be called before configureActionBar
    setContentView(R.layout.all_in_one);

    if (mIsTabletConfig) {
        mDateRange = (TextView) findViewById(R.id.date_bar);
        mWeekTextView = (TextView) findViewById(R.id.week_num);
    } else {
        mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
    }

    // configureActionBar auto-selects the first tab you add, so we need to
    // call it before we set up our own fragments to make sure it doesn't
    // overwrite us
    configureActionBar(viewType);

    mHomeTime = (TextView) findViewById(R.id.home_time);
    mMiniMonth = findViewById(R.id.mini_month);
    if (mIsTabletConfig && mOrientation == Configuration.ORIENTATION_PORTRAIT) {
        mMiniMonth.setLayoutParams(
                new RelativeLayout.LayoutParams(mControlsAnimateWidth, mControlsAnimateHeight));
    }
    mCalendarsList = findViewById(R.id.calendar_list);
    mMiniMonthContainer = findViewById(R.id.mini_month_container);
    mSecondaryPane = findViewById(R.id.secondary_pane);

    // Must register as the first activity because this activity can modify
    // the list of event handlers in it's handle method. This affects who
    // the rest of the handlers the controller dispatches to are.
    mController.registerFirstEventHandler(HANDLER_KEY, this);

    initFragments(timeMillis, viewType, icicle);

    // Listen for changes that would require this to be refreshed
    SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    mContentResolver = getContentResolver();
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java

protected void resetKeyboardTheme(@NonNull KeyboardTheme theme) {
    final int keyboardThemeStyleResId = getKeyboardStyleResId(theme);

    final int[] remoteKeyboardThemeStyleable = theme.getResourceMapping()
            .getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewTheme);
    final int[] remoteKeyboardIconsThemeStyleable = theme.getResourceMapping()
            .getRemoteStyleableArrayFromLocal(R.styleable.AnyKeyboardViewIconsTheme);

    final int[] padding = new int[] { 0, 0, 0, 0 };

    int keyTypeFunctionAttrId = R.attr.key_type_function;
    int keyActionAttrId = R.attr.key_type_action;
    int keyActionTypeDoneAttrId = R.attr.action_done;
    int keyActionTypeSearchAttrId = R.attr.action_search;
    int keyActionTypeGoAttrId = R.attr.action_go;

    HashSet<Integer> doneLocalAttributeIds = new HashSet<>();
    TypedArray a = theme.getPackageContext().obtainStyledAttributes(keyboardThemeStyleResId,
            remoteKeyboardThemeStyleable);
    final int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        final int remoteIndex = a.getIndex(i);
        final int localAttrId = R.styleable.AnyKeyboardViewTheme[remoteIndex];
        if (setValueFromTheme(a, padding, localAttrId, remoteIndex)) {
            doneLocalAttributeIds.add(localAttrId);
            if (localAttrId == R.attr.keyBackground) {
                //keyTypeFunctionAttrId and keyActionAttrId are remote
                final int[] keyStateAttributes = theme.getResourceMapping()
                        .getRemoteStyleableArrayFromLocal(KEY_TYPES);
                keyTypeFunctionAttrId = keyStateAttributes[0];
                keyActionAttrId = keyStateAttributes[1];
            }// www.  j  ava2 s.co m
        }
    }
    a.recycle();
    // taking icons
    int iconSetStyleRes = getKeyboardIconsStyleResId(theme);
    if (iconSetStyleRes != 0) {
        a = theme.getPackageContext().obtainStyledAttributes(iconSetStyleRes,
                remoteKeyboardIconsThemeStyleable);
        final int iconsCount = a.getIndexCount();
        for (int i = 0; i < iconsCount; i++) {
            final int remoteIndex = a.getIndex(i);
            final int localAttrId = R.styleable.AnyKeyboardViewIconsTheme[remoteIndex];
            if (setKeyIconValueFromTheme(theme, a, localAttrId, remoteIndex)) {
                doneLocalAttributeIds.add(localAttrId);
                if (localAttrId == R.attr.iconKeyAction) {
                    //keyActionTypeDoneAttrId and keyActionTypeSearchAttrId and keyActionTypeGoAttrId are remote
                    final int[] keyStateAttributes = theme.getResourceMapping()
                            .getRemoteStyleableArrayFromLocal(ACTION_KEY_TYPES);
                    keyActionTypeDoneAttrId = keyStateAttributes[0];
                    keyActionTypeSearchAttrId = keyStateAttributes[1];
                    keyActionTypeGoAttrId = keyStateAttributes[2];
                }
            }
        }
        a.recycle();
    }
    // filling what's missing
    KeyboardTheme fallbackTheme = KeyboardThemeFactory.getFallbackTheme(getContext().getApplicationContext());
    final int keyboardFallbackThemeStyleResId = getKeyboardStyleResId(fallbackTheme);
    a = fallbackTheme.getPackageContext().obtainStyledAttributes(keyboardFallbackThemeStyleResId,
            R.styleable.AnyKeyboardViewTheme);

    final int fallbackCount = a.getIndexCount();
    for (int i = 0; i < fallbackCount; i++) {
        final int index = a.getIndex(i);
        final int attrId = R.styleable.AnyKeyboardViewTheme[index];
        if (doneLocalAttributeIds.contains(attrId))
            continue;
        setValueFromTheme(a, padding, attrId, index);
    }
    a.recycle();
    // taking missing icons
    int fallbackIconSetStyleId = fallbackTheme.getIconsThemeResId();
    a = fallbackTheme.getPackageContext().obtainStyledAttributes(fallbackIconSetStyleId,
            R.styleable.AnyKeyboardViewIconsTheme);

    final int fallbackIconsCount = a.getIndexCount();
    for (int i = 0; i < fallbackIconsCount; i++) {
        final int index = a.getIndex(i);
        final int attrId = R.styleable.AnyKeyboardViewIconsTheme[index];
        if (doneLocalAttributeIds.contains(attrId))
            continue;
        setKeyIconValueFromTheme(fallbackTheme, a, attrId, index);
    }
    a.recycle();
    //creating the key-drawable state provider, as we suppose to have the entire data now
    mDrawableStatesProvider = new KeyDrawableStateProvider(keyTypeFunctionAttrId, keyActionAttrId,
            keyActionTypeDoneAttrId, keyActionTypeSearchAttrId, keyActionTypeGoAttrId);

    // settings.
    // don't forget that there are THREE padding,
    // the theme's and the
    // background image's padding and the
    // View
    Drawable keyboardBackground = super.getBackground();
    if (keyboardBackground != null) {
        Rect backgroundPadding = new Rect();
        keyboardBackground.getPadding(backgroundPadding);
        padding[0] += backgroundPadding.left;
        padding[1] += backgroundPadding.top;
        padding[2] += backgroundPadding.right;
        padding[3] += backgroundPadding.bottom;
    }
    setPadding(padding[0], padding[1], padding[2], padding[3]);

    final Resources res = getResources();
    final int viewWidth = (getWidth() > 0) ? getWidth() : res.getDisplayMetrics().widthPixels;
    mKeyboardDimens.setKeyboardMaxWidth(viewWidth - padding[0] - padding[2]);

    mPaint.setTextSize(mKeyTextSize);

    mKeyBackground.getPadding(mKeyBackgroundPadding);
}