将弹窗的大部分功能都给抽出,在自定义弹窗的时候,只需要写一个布局,剩余大量重复代码
示例
public classBaseDialog {
privateActivitymActivity;
privateDialogdialog;
privateHashMapmap=newHashMap<>();
publicBaseDialog(Activity activity, intlayoutId) {
this.mActivity= activity;
dialog=newDialog(mActivity,R.style.dialog);
View view = View.inflate(activity,layoutId, null);
dialog.setContentView(view);
map.clear();
try{
getAllViews((ViewGroup) view);
}catch(Exception e) {
e.printStackTrace();
}
}
private voidgetAllViews(ViewGroup viewGroup) {
intcount = viewGroup.getChildCount();
for(inti =0;i < count;i++) {
View childAt = viewGroup.getChildAt(i);
if(childAtinstanceofViewGroup) {
try{
getAllViews((ViewGroup) childAt);
}catch(Exception e) {
e.printStackTrace();
}
}
intid = childAt.getId();
if(id != -1) {
map.put(id,childAt);
}
}
}
publicStringgetText(intid) {
View view =map.get(id);
try{
if(viewinstanceofButton) {
Button v = (Button) view;
returnv.getText().toString().trim();
}
if(viewinstanceofEditText) {
EditText v = (EditText) view;
returnv.getText().toString().trim();
}
if(viewinstanceofTextView) {
TextView v = (TextView) view;
returnv.getText().toString().trim();
}
}catch(Exception e) {
return"";
}
return"";
}
//设置控件文字
public voidsetText(String msg, intid) {
View view =map.get(id);
try{
if(viewinstanceofTextView) {
TextView v = (TextView) view;
v.setText(msg);
}
if(viewinstanceofEditText) {
EditText v = (EditText) view;
v.setText(msg);
}
if(viewinstanceofButton) {
Button v = (Button) view;
v.setText(msg);
}
}catch(Exception e) {
LogUtils.e("BaseDialog","该控件不可设置文字");
}
}
/**
*@time2017/7/13 10:41
*@desc设置点击监听
*/
public voidsetOnClickListener(View.OnClickListener listener) {
try{
for(Integer i :map.keySet()) {
View view =map.get(i);
if(!view.hasOnClickListeners()) {
view.setOnClickListener(listener);
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
/**
*@time2017/7/13 11:26
*@desc弹窗显示
*/
//0全屏
//1居于底部
public voidshow(inttype){
Window window =dialog.getWindow();
WindowManager.LayoutParams params = window.getAttributes();
switch(type){
case0:
params.width= WindowManager.LayoutParams.MATCH_PARENT;
params.height= WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(params);
break;
case1:
params.width= WindowManager.LayoutParams.MATCH_PARENT;
window.setAttributes(params);
window.setGravity(Gravity.BOTTOM);
break;
}
show();
}
/**
*@time2017/7/13 9:47
*@desc弹窗显示
*/
public voidshow() {
try{
dialog.show();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
*@time2017/7/13 9:47
*@desc弹窗消失
*/
public voiddismiss() {
try{
dialog.dismiss();
}catch(Exception e) {
e.printStackTrace();
}
}
}