5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Fragment/View 中でどの Activity から利用されているか判定する

Last updated at Posted at 2015-11-04

Fragment の場合

getActivity() で Activity への参照を取得し getLocalClassName() メソッドでクラス名(文字列)を取得します。

Activity activity = getActivity();
if (activity != null) {
    Log.i("foo", activity.getLocalClassName());
}

あとはクラス名(文字列)を利用して ifswitch 文で条件分岐すれば。

View の場合

<Viewのインスタンス>.getContext() で Activity への参照が取得できるので、あとは上記と同じです。

Activity activity = (Activity) mFooViewInstance.getContext();
if (activity != null) {
    Log.i("foo", activity.getLocalClassName());
}

ほか

switch 文でうまく扱えないですが、それでもいいなら instanceof で判定してもよいかと思います。文字列でないのでクラス名の変更に強い。

if (activity instanceof FooActivity) {
	//...
}
5
8
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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?