Ari*_*aro 20 android android-fragments
在API 23之前,我使用Fragment的onAttach方法来获取我的侦听器实例,然后在onDetach中清理引用.例如:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mListener = null;
try {
mListener = (SellFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SellFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
Run Code Online (Sandbox Code Playgroud)
在onAttach(Context context)中进行相同的检查是否安全,或者是否有更好的方法来获取持有者活动实例?
Zso*_*ter 27
检查源代码:
/**
* Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
public void onAttach(Context context) {
mCalled = true;
final Activity hostActivity = mHost == null ? null : mHost.getActivity();
if (hostActivity != null) {
mCalled = false;
onAttach(hostActivity);
}
}
/**
* @deprecated Use {@link #onAttach(Context)} instead.
*/
@Deprecated
public void onAttach(Activity activity) {
mCalled = true;
}
Run Code Online (Sandbox Code Playgroud)
因此,如果存在主机活动onAttach(Activity activity)则调用它onAttach(Context context).你可以onAttach(Activity activity)安全使用.
如 Zsolt Mester 的回答所示,onAttach(Activity activity)不推荐使用onAttach(Context context). 因此,您需要做的就是检查以确保上下文是一个活动。
在 Android Studio 中,如果您转到File > New > Fragment,您可以获得包含正确语法的自动生成的代码。
import android.support.v4.app.Fragment;
...
public class MyFragment extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate fragment layout
return inflater.inflate(R.layout.fragment_myfragment, container, false);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Run Code Online (Sandbox Code Playgroud)
笔记
由于父 Activity 必须实现我们的OnFragmentInteractionListener(任意命名的接口),因此检查(context instanceof OnFragmentInteractionListener)可确保上下文实际上是 Activity。
请注意,我们正在使用支持库。否则onAttach(Context context)不会被 API 23 之前的 Android 版本调用。
也可以看看
| 归档时间: |
|
| 查看次数: |
22823 次 |
| 最近记录: |