getArguments()
setArguments()
methods seem very useful when it comes to instantiating a Fragment using a static method.
ieMyfragment.createInstance(String msg)
How to do it?
Fragment code
public MyFragment extends Fragment {
private String displayMsg;
private TextView text;
public static MyFragment createInstance(String displayMsg)
{
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.setString("KEY",displayMsg);
fragment.setArguments(args); //set
return fragment;
}
@Override
public void onCreate(Bundle bundle)
{
displayMsg = getArguments().getString("KEY"): // get
}
@Override
public View onCreateView(LayoutInlater inflater, ViewGroup parent, Bundle bundle){
View view = inflater.inflate(R.id.placeholder,parent,false);
text = (TextView)view.findViewById(R.id.myTextView);
text.setText(displayMsg) // show msg
returm view;
}
}
Let's say you want to pass a String while creating an Instance. This is how you will do it.
MyFragment.createInstance("This String will be shown in textView");
1) Why Myfragment.getInstance(String msg) is preferred over new MyFragment(String msg)?
2) Sample code on Fragments