LoginSignup
12
16

More than 5 years have passed since last update.

Activity間でグローバル関数などを使う

Last updated at Posted at 2014-08-19

Applicationクラスを継承した独自クラスを作成

Globals.java
public class Globals extends Application {

    boolean mIsBound;
    boolean connected;
    int length;
    int[] buffer;
    byte[] data;

    public void init(){
        mIsBound = false;
    }

    public void showToast(String text) {
        Toast.makeText(this, text,Toast.LENGTH_SHORT).show();
    }
}

AndroidManifest.xmlにクラスを記述

applicationタグに、 android:name=".Globals"を挿入する。

AndroidManifest.xml
<application
    android:name=".Globals"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    ....
</application>

Activityで使う

MainActivity.java
Globals globals;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // getApplication()でアプリケーションクラスのインスタンスを拾う
    globals = (Globals)this.getApplication();

    //変数を使う
    int l = globals.length;

    //初期化する
    globals.init();

    //トーストする
    globals.showToast("hoge");
}
12
16
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
12
16