是否厭煩了寫各種onActivityResult?不要急,透明fragment來幫你
雖然fragment坑死人不償命,但是不寫view,只作為輔助功能來使用,還是很好用的.
思路來自於:RxPermissionsFragment
基類
public abstract class BaseTransFragment extends Fragment {
protected FragmentActivity activity;//自行儲存activity引導,絕對不用getActivity()這個坑貨
protected void setHostActivity(FragmentActivity activity) {
this.activity = activity;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);//避免旋轉時fragment銷燬重建
}
}
複製程式碼
工具方法:
public static <T extends BaseTransFragment> T getTransFragment(FragmentActivity fragmentActivity,
String fragmentTag, Callable<T> newIntance) {
try {
FragmentManager fragmentManager = fragmentActivity.getSupportFragmentManager();
T fragment = findFragment(fragmentManager, fragmentTag);
boolean isNewInstance = fragment == null;
if (isNewInstance) {
fragment = newIntance.call();
fragmentManager.beginTransaction()
.add(fragment, fragmentTag)
.commitAllowingStateLoss();//避免資料儲存和恢復導致的crash
fragmentManager.executePendingTransactions();
}
fragment.setHostActivity(fragmentActivity);
return fragment;
} catch (Exception e) {
e.printStackTrace();
try {
return newIntance.call();
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
}
}
private static <T extends BaseTransFragment> T findFragment(FragmentManager fragmentManager, String fragmentTag) {
Fragment fragment = fragmentManager.findFragmentByTag(fragmentTag);
if (fragment == null) {
return null;
}
return (T) fragment;
}
複製程式碼
例子:
1.寫了一個VendorPayTransFragment繼承basefragment,沒有介面,裡面封裝好了整套流程,處理了各種onactivityresult,許可權,網路請求等等,然後,提供一個靜態方法,提供輸入和回撥:
public static void startOrder(FragmentActivity activity, BaseQRPayCalInfo info, IVendorPayCallback callback) {
VendorPayTransFragment fragment = getTransFragment(activity, "offlineorder",
new Callable<VendorPayTransFragment>() {
@Override
public VendorPayTransFragment call() throws Exception {
return VendorPayTransFragment.newInstance(info);
}
});
fragment.setCallback(callback);
fragment.startScanOrder();
}
複製程式碼
- 拍照/圖片選擇-裁剪-壓縮整個流程,封裝成一個工具方法:
TakePhotoUtil.startPickOne(this, false, new TakeOnePhotoListener() {
@Override
public void onSuccess(String s) {
showImg(filePath);
}
@Override
public void onFail(String path, String msg) {
MyToast.errorBigL(s1);
}
@Override
public void onCancel() {
}
});
複製程式碼