Potato04 The end of confusion of callback between activity and fragment.
-
Upload
toshihiro-yagi -
Category
Documents
-
view
1.526 -
download
5
Transcript of Potato04 The end of confusion of callback between activity and fragment.
The end of confusion of callback between activity and fragment.
2014-02-12 potatotips #4 Toshihiro Yagi
About meTwitter : @sys1yagi Blog : http://sys1yagi.com !!Android Engineer at
出てます。
http://www.amazon.co.jp/gp/product/4798040029/
Problem• How communicate between Activity and Fragment?
Activity Fragment
?
@Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallback = (Listener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement Listener"); } }
#01 Implement a interface in a Activity
Communicating with Other Fragments http://developer.android.com/training/basics/fragments/communicating.html
Declare InterfaceImplements Interface
いいんだけどダサくね?
ClassCastException
mCallback = (Listener) activity;
try{}catch{}
throw new
extends Activity implements Listener{
#02 No rotation or receive config changes.
Set Interface
Declare InterfaceNo rotation
でも結局Activity破棄-再生成で死ぬよね?
@Override protected void onCreate(Bundle save) { super.onCreate(savedInstanceState); bus.register(this); } ! @Subscribe private void onClick(OnClickEvent event){ //do something }
bus.post(new OnClickEvent(10));
#03 Using message bus.
Otto
Otto http://square.github.io/otto/
Message Bus
濫用するときつい コンテキスト遠い
#04 Using Roboguice or Dagger, etc…
Injector Declare Interface
Module
Depend on
OK but, exaggerated
In the first place…• なんでActivity-Fragment間連携の為に色々な罠をかいくぐらなければならないんだ
• ついでにDialogFragment-Fragment間もだるい
• 再生成を別々にするのがそもそもおかしくね?
• 基本的にActivity←Fragmentの一方向依存だよね
• 統一的で簡単で罠のない書き方がほしい
無かったら作る
indirect injector
SimplifyIndirect Injector
add dependency
inject request
Declare Interface
@Override protected void onCreate(Bundle save) { super.onCreate(savedInstanceState); IndirectInjector.addDependency(this, mListener); }
@Inject Listener mListener; !@Override public void onActivityCreated(Bundle savedInstanceState) { IndirectInjector.inject(getActivity(), this); }
SimplifyIndirect Injector
add dependency
inject request
Declare Interface
Good bye confusion• build.gradleにdependencies書いて
• Fragmentの必要なフィールドに@Injectつけて
• Activity側でIndirectInjectorにaddDependency()する
• FragmentのonActivityCreated()でIndirectInjectorのinject()を呼ぶ
• どういう再生成が走っても大丈夫
Enjoy!
おわりに
https://github.com/sys1yagi/indirect-injector
Welcome your pull request!
GitHub活動を通して個人のキャリアを積みつつ仕事の成果を出したい
We are hiring!!!