如果您正在嘗試通過添加片段的活動來創建該片段,我已將祝賀片添加到FragmentListener
並從活動中進行設置。這是我的基本BaseFragment
類,我所有的片段擴展:
public class BaseFragment extends Fragment {
public Context context;
public Activity activity;
public FragmentListener fragmentListener;
private boolean attached = false;
public BaseFragment() {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!isAttached()) {
this.context = activity;
this.activity = activity;
if (this.fragmentListener != null) {
this.fragmentListener.onAttached();
}
setAttached(true);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (!isAttached()) {
this.context = context;
this.activity = (Activity) context;
if (this.fragmentListener != null) {
this.fragmentListener.onAttached();
}
setAttached(true);
}
}
@Override
public void onDetach() {
super.onDetach();
setAttached(false);
if (this.fragmentListener != null){
this.fragmentListener.onDetached();
}
}
public void setFragmentListener(FragmentListener fragmentListener) {
this.fragmentListener = fragmentListener;
}
public View.OnClickListener onBackTapped = new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
};
public boolean isAttached() {
return attached;
}
public void setAttached(boolean attached) {
this.attached = attached;
}
public boolean isPermissionGranted(String permission){
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public boolean ifShouldShowRationaleForPermission(String permission){
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}
public void showPermissionRequest(Activity activity, int requestCode, String... permissions){
ActivityCompat.requestPermissions(activity, permissions, requestCode);
}
}
這樣一來,我可以在我的活動做到這一點:
MyFragment myFragment = new MyFragment();
myfragment.setFragmentListener(new FragmentListener() {
@Override
public void onAttached() {
// Stuff I want to do when it is attached
}
@Override
public void onDetached() {
// Stuff I want to do when it is detached
}
});
fragmentManager.beginTransaction()
.add(R.id.container, myFragment)
.commit();
然後我可以加我想要的任何代碼時,碎片也它是各種各樣的東西。
祝你好運!