Created
September 21, 2016 22:48
-
-
Save twiceyuan/fe11ca5bb0cced3ae8d19f4b03422aac to your computer and use it in GitHub Desktop.
使用透明 Activity 作为 Dialog 的 Context 的封装方法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.content.Intent; | |
import android.os.Bundle; | |
/** | |
* Created by twiceYuan on 10/8/15. | |
* | |
* 因为 Dialog 需要作为 Activity 作为 Context,所以在服务中如果需要弹出对话框就需要该界面支持 | |
*/ | |
public class DialogContainerActivity extends Activity { | |
private static DialogContextProvider mContextProvider; | |
public static void show(DialogContextProvider contextProvider) { | |
mContextProvider = contextProvider; | |
Intent intent = new Intent(App.getApp(), DialogContainerActivity.class); | |
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); | |
App.getApp().startActivity(intent); | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
mContextProvider.getActivity(this); | |
} | |
public interface DialogContextProvider { | |
void getActivity(Activity activity); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 没有 Activity 的 Context 时调用的(注意: 在 Activity 中调用会触发原 Activity 的 onPause) | |
*/ | |
public static void simpleMessage(String message, OnConfirm onConfirm, OnCancel onCancel) { | |
DialogContainerActivity.show(context -> { | |
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AppTheme_Dialog); | |
builder.setMessage(message); | |
if (onConfirm != null) { | |
builder.setPositiveButton("确定", (dialog, which) -> onConfirm.onConfirm()); | |
} | |
if (onCancel != null) { | |
builder.setNegativeButton("取消", (dialog, which) -> onCancel.cancel()); | |
} | |
AlertDialog dialog = builder.create(); | |
dialog.show(); | |
closeDialogContainer(dialog, context); | |
}); | |
} | |
/** | |
* 关闭对话框外部的 Activity | |
*/ | |
private static void closeDialogContainer(AlertDialog dialog, Activity context) { | |
dialog.setOnDismissListener(d -> context.finish()); | |
} | |
/** | |
* 确定回调接口 | |
*/ | |
public interface OnConfirm { | |
void onConfirm(); | |
} | |
/** | |
* 取消回调接口 | |
*/ | |
public interface OnCancel { | |
void cancel(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment