在Android开发过程中,有时候我们加载数据,为了更好的用户体验,往往会使用progress去体现数据正在加载中,这个是系统提供的,我们可以直接调用。但有时候感觉还是会不太满足于我们的需求,所以我们就试图用遮罩层去更好的改观用户体验。
直接上代码:
/**
* 等待弹屏
* @author
* @date
*/
public class MainActivity extends Activity implements OnClickListener{
PopupWindow popupWindow;
private WaitScreen waitScreen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (popupWindow!=null) {
waitScreen.close();
}
}
}, 3*1000);
}
@Override
public void onAttachedToWindow() {
show();
super.onAttachedToWindow();
}
private void show() {
waitScreen=new WaitScreen(this);
popupWindow=waitScreen.show();
}
@Override
public void onClick(View v) {
show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
if (popupWindow!=null) {
waitScreen.close();
return true;
}
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
/**
* 等待弹屏
* @author
* @date
*/
public class WaitScreen {
private PopupWindow popupWindow;
private Context context;
private View view;
public WaitScreen(Context context) {
this.context=context;
view=LayoutInflater.from(context).inflate(R.layout.poplayout, null);
popupWindow=new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
/**
* 弹出等待提示框
* @author
* @date
* @return
*/
public PopupWindow show() {
popupWindow.showAsDropDown(view);
return popupWindow;
}
/**
* 以动画的方式关闭等待弹屏
* @author
* @date
*/
public void close() {
if (popupWindow!=null&&popupWindow.isShowing()) {
popupWindow.setFocusable(false);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
popupWindow.dismiss();
}
}, 500);
View progressBar1=view.findViewById(R.id.progressBar1);
progressBar1.setVisibility(View.GONE);
View left=view.findViewById(R.id.left);
View right=view.findViewById(R.id.right);
TranslateAnimation leftAnimation= new TranslateAnimation(0,-left.getWidth(),0f,0f);
leftAnimation.setDuration(500);//设置动画持续时间为3秒
leftAnimation.setInterpolator(context, android.R.anim.overshoot_interpolator);//设置动画插入器
leftAnimation.setFillAfter(true);//设置动画结束后保持当前的位置(即不返回到动画开始前的位置)
left.startAnimation(leftAnimation);
TranslateAnimation rightAnimation= new TranslateAnimation(0f,left.getWidth(),0f,0f);
rightAnimation.setDuration(500);//设置动画持续时间为3秒
rightAnimation.setInterpolator(context, android.R.anim.overshoot_interpolator);//设置动画插入器
rightAnimation.setFillAfter(true);//设置动画结束后保持当前的位置(即不返回到动画开始前的位置)
right.startAnimation(rightAnimation);
}
}
/**
* 关闭弹屏
* @author
* @date
*/
public void dismiss() {
if (popupWindow!=null&&popupWindow.isShowing()) {
popupWindow.dismiss();
}
}
}
这样我们就可以实现在加载数据的时候,显示一层正在加载数据的遮罩效果。