Anteriormente eu estou usando onAttach (Activity activity)para chegar contextemFragment
Problema
O onAttach (Activity activity)método foi descontinuado no nível 23 da API.
Solução
Agora, para obter contexto Fragment, podemos usaronAttach (Context context)
onAttach (Context context)
- Chamado quando um fragmento é anexado pela primeira vez a ele
context. onCreate(Bundle)será chamado depois disso.
Documentação
/**
* Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
@CallSuper
public void onAttach(Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
CÓDIGO DE AMOSTRA
public class FirstFragment extends Fragment {
private Context mContext;
public FirstFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rooView=inflater.inflate(R.layout.fragment_first, container, false);
Toast.makeText(mContext, "THIS IS SAMPLE TOAST", Toast.LENGTH_SHORT).show();
// Inflate the layout for this fragment
return rooView;
}
}
NOTA
Também podemos usar getActivity()para entrar context, Fragments
mas getActivity()podemos retornar nullse o seu fragmentnão estiver atualmente anexado a um pai activity,