LoginSignup
14
13

More than 5 years have passed since last update.

Android 小ネタ集

Last updated at Posted at 2016-05-24

メモ書き程度に小ネタを記入します。

Activity遷移でアニメーションを消す方法

いらないアニメーションを消すコードです。

java
Intent intent = new Intent(Sample.this, Sample2.class);
startActivity(intent);
overridePendingTransition(0, 0); // このコードでアニメーションを消す

Activity#finish()でアニメーションを消す場合

java
@Override
public void finish() { // finish()メソッドをオーバライドして編集
    super.finish();
    overridePendingTransition(0, 0); // このコードでアニメーションを消す
}

全てのActivityを消去し、アプリを最初から始める方法

ホームボタンや、終了ボタンに使用するかも

java
Intent intent = new Intent(Page2Activity.this, TsubakiMapActivity.class);
// Intentの設定でFLAG_ACTIVITY_CLEAR_TOPとFLAG_ACTIVITY_NEW_TASKを設定する。
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

画像サイズをディスプレイサイズにする方法

Androidにて、縦横比を固定にしたまま画像をディスプレイサイズにリサイズするスクリプト

java
public static Bitmap resizeBitmapToDisplaySize(Activity activity, Bitmap src){
        int srcWidth = src.getWidth(); // Bitmap width
        int srcHeight = src.getHeight(); // Bitmap height

        // Get the screen size
        Matrix matrix = new Matrix();
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float screenWidth = (float) metrics.widthPixels;
        float screenHeight = (float) metrics.heightPixels;

        float widthScale = screenWidth / srcWidth;
        float heightScale = screenHeight / srcHeight;

        if (widthScale > heightScale) {
            matrix.postScale(heightScale, heightScale);
        } else {
            matrix.postScale(widthScale, widthScale);
        }

        // reSize
        Bitmap dst = Bitmap.createBitmap(src, 0, 0, srcWidth, srcHeight, matrix, true);
        src = null;
        return dst;
    }

libsフォルダにあるjarファイルを一括でインポートする方法

Android Studioでjarファイルを使用するとき、build.gradleのdependenciesに以下の記述を加えると一括でインポートされます。

build.gradle
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

明示的にパーミッション許可をリクエストする方法

OSバージョン「6.0(Marshmallow)」からActivity#requestPermissionsが使用できます。
※同バージョンよりパーミッションの許可がデフォルトでOFFになっている場合があります。

activity
if(Build.VERSION.SDK_INT >= 23){
    // 6.0以降はコメントアウトした処理をしないと初回はパーミッションがOFFになっています。
    requestPermissions(new String[]{
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}
14
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
13