Trước đây tôi đang sử dụng onAttach (Activity activity)để contextvàoFragment
Vấn đề
Các onAttach (Activity activity)phương pháp được tán thành trong mức API 23.
Giải pháp
Bây giờ để có được bối cảnh trong Fragmentchúng ta có thể sử dụngonAttach (Context context)
onAttach (Context context)
- Được gọi khi một mảnh đầu tiên được gắn vào nó
context. onCreate(Bundle)sẽ được gọi sau này.
Tài liệu
/**
* 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);
}
}
MẪU MÃ
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;
}
}
GHI CHÚ
Chúng tôi cũng có thể sử dụng getActivity()để contextvào Fragments
nhưng getActivity()có thể quay lại nullnếu fragmenthiện tại bạn chưa gắn bó với cha mẹ activity,