一、场景
在很多时候我们都需要背景透明,或者提示信息,可以采用Dialog来实现,简单方便。
public class BaseDialog extends Dialog { protected Context mContext; public BaseDialog(@NonNull Context context) { super(context); initView(context); } public BaseDialog(@NonNull Context context, @StyleRes int themeResId) { super(context, themeResId); initView(context); } protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); initView(context); } private void initView(Context context) { this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setBackgroundDrawableResource(R.drawable.base_dialog_bg); mContext = context; Window window = this.getWindow(); mLayoutParams = window.getAttributes(); mLayoutParams.alpha = 1f; window.setAttributes(mLayoutParams); if (mLayoutParams != null) { mLayoutParams.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT; mLayoutParams.gravity = Gravity.CENTER; } } public BaseDialog(Context context, float alpha, int gravity) { super(context); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setBackgroundDrawableResource(R.drawable.base_dialog_bg); mContext = context; Window window = this.getWindow(); mLayoutParams = window.getAttributes(); mLayoutParams.alpha = 1f; window.setAttributes(mLayoutParams); if (mLayoutParams != null) { mLayoutParams.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT; mLayoutParams.gravity = gravity; } } }
二、具体场景
public class UpdateDialog extends BaseDialog implements View.OnClickListener { public UpdateDialog(@NonNull Context context) { super(context); } public UpdateDialog(@NonNull Context context, String title) { super(context); initView(context, title); } private void initView(Context context, String title) { final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.layout_item_update, null, false); view.findViewById(R.id.btn_cancel).setOnClickListener(this); view.findViewById(R.id.btn_ensure).setOnClickListener(this); TextView mTips = (TextView) view.findViewById(R.id.tv_tip); mTips.setText(title); mLayoutParams.gravity = Gravity.CENTER; setContentView(view); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_ensure://确认 if (mCallback != null) { mCallback.ensure(); } break; case R.id.btn_cancel://取消 dismiss(); break; } } private Callback mCallback; public void setCallback(Callback mCallback) { this.mCallback = mCallback; } public interface Callback { void ensure(); } }