18
12

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にクラスを渡す方法

Last updated at Posted at 2016-03-31

Fragment間で値を受け渡しをする場合
Bundleにセットするだけで簡単にできます。

Bundle bundle = new Bundle();
bundle.putString("hoge", "hoge");
bundle.putString("fuga", "fuga");

Fragment fragment = new Fragment();
fragment.setArguments(bundle);

//onCreateView内
Bundle bundle = getArguments();
String hoge = bundle.getString("hoge"); 
String fuga = bundle.getString("fuga"); 

ただクラスの受け渡しをしたい場合がありますよね

public class Clazz{

	private String hoge;
	private String fuga;
}

その方法ですが、
まず、ClazzクラスにSerializableインターフェースを実装します。

public class Clazz implements Serializable{
        //略...
}

あとはClazzクラスをputSerializableでBundleにセットして渡すだけです。

Clazz clazz = new Clazz();
clazz.setHoge("hoge");
clazz.setFuga("fuga");
        
Bundle bundle = new Bundle();
bundle.putSerializable("CLASS", clazz);
        
Fragment fragment = new Fragment();
fragment.setArguments(bundle);

//取り出し onCreateView内で
Bundle bundle = getArguments();
Person person = (Person)bundle.getSerializable("CLASS");
Log.d("HOGE",String.valueOf(class.getHoge()));
Log.d("FUGA",String.valueOf(class.getFuga()));
18
12
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
18
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?