此前使用<代码>onAttach(活动)到context
载于Fragment
问题
https://developer.android.com/vis/android/app/Fragment.html#onAttach(android.app.Actative)”rel=“noreferer”>onAttach(活动)
已在第23级修改了方法。
Solution
现在,可在<代码>Fragment中查阅,我们可使用>onAttach (Context context)
/a>。
<><>>>> Attach (Context context)
- Called when a fragment is first attached to its
context
. onCreate(Bundle)
will be called after this.
文件
/**
* 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);
}
}
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;
}
}
NOTE
We can also use getActivity()
to get context
in Fragments
but getActivity()
can return null
if the your fragment
is not currently attached to a parent activity
,