-
Notifications
You must be signed in to change notification settings - Fork 22
arg module provides @Arg annotation.
Annotation for generating newInstance()
methods for your Fragment classes.
Without using this library you would have to write this:
public class MyFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_DATA = "arg_data";
public static MyFragment newInstance(String text, MyData data) {
MyFragment frag = new MyFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putParcelable(ARG_DATA, data);
frag.setArguments(args);
return frag;
}
private String mText;
private MyData mData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mText = getArguments().getString(ARG_TEXT);
mData = (MyData) getArguments().getParcelable(ARG_DATA);
}
}
But with this library you can write this:
public class MyFragment extends Fragment {
@Arg
String mText;
@Arg
MyData mData;
}
Class blade.F
(= Fragment) is automatically generated for you.
This class contains 1 method for each Fragment
class with annotated fields:
-
X newX(T1 arg1[, T2 arg2, ...])
- Creates new instance of classX
.
e.g. for MyFragment
class it contains method named newMyFragment(...)
with 2 parameters: String
and MyData
.
So you can easily create new fragment by calling:
F.newMyFragment("some-string", new MyData());
And given values will be injected to the corresponding fields annotated with @Arg
at the beginning of onCreate(Bundle)
method.
Class blade.F
is not final
so that you can extend it and add more methods.
Since version 2.6.0
you can supply a class parameter to the annotation.
This class should implement the blade.Bundler interface
and you can use it to provide custom serialization and deserialization for your types.
Example:
public class MyFragment extends Fragment {
@Arg(MyTypeBundler.class)
MyType mMyType;
}
public class MyTypeBundler implements Bundler<MyType> {
void save(@Nullable final MyType value, @NonNull final Bundle state) {
// save given value to the state
}
@Nullable
MyType restore(@NonNull final Bundle state) {
// restore and return value from state
}
}