I have a class like this:
public Class Row {
private int data = 0;
private View.OnClickListener callback = null;
public void setData(int a) { data = a; }
public void setOnClickListener(View.OnClickListener i) { callback = i; }
}
And I like to provide an instance of this class to a Fragment. Considering a member interface, I cannot Serialize or Parcel this class and send it via setArgument()
.
What do you suggest for providing this class to my Fragment? I thought of 3 methods, but I wonder what is better:
1-Providing class via a setter functions:
Myfrag frag = new Myfrag();
Row r = new Row();
r.setOnClickListener(this);
frag.setRow(r);
getSupportFragmentManager().beginTrasaction().add(R.id.containder_id, frag).commit();
Some people discourage using this method, because it seems that this method may fail on Fragment
recreation.
2-Proving class via a callback interface
In this case activity provides an interface which returns class for Fragment
:
public class MyActivity extend Activity implements Myfrag.OnGetRow{
private Row mRow = null;
...
public createFragment() {
Myfrag frag = new Myfrag();
mRow = new Row();
mRow.setOnClickListener(this);
getSupportFragmentManager().beginTrasaction().add(R.id.containder_id, frag).commit();
}
public Row getRow() {
return mRow;
}
}
And in Fragment
:
public class MyFrag extend Fragment {
...
public interface OnGetRow {
public Row getRow();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
OnGetRow mCallback = null;
try {
mCallback = (OnGetRow) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
mRow = mCallback.getRow();
}
}
3-Just provide a public function for activity, and call it in onAttach()
of Fragment
.
What do you suggest for this problem?