最近作项目时,遇到一种状况,请求服务器时,要把结果提示给用户,但是因为网络缘由,反应不是很灵敏,用户就会屡次点击一个或恶意连着快速点击多个能够出发提示的按钮,这时,就会连着toast出好几个提示,用户体验至关很差,因而想着写一个弹出框,来覆盖屏幕(中间一个TextView,四周都是透明的),这样既能够友情提示用户,又能够防止上述现象出现。
android
布局文件:
服务器
<?xml version="1.0" encoding="utf-8"?>网络
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"ide
android:layout_width="match_parent"工具
android:layout_height="match_parent"布局
android:gravity="center"this
android:background="#550f0f0f"spa
android:id="@+id/lay_pop"xml
android:orientation="vertical" >utf-8
<TextView
android:layout_width="80dp"
android:layout_height="40dp"
android:background="#55ffffff"
android:id="@+id/tv_pop"
android:gravity="center"/>
</LinearLayout>
工具类:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.PopupWindow;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class PopWindowUtils {
public static PopupWindow getMyPopWindow(Context context,String content){
final View view1=LayoutInflater.from(context).inflate(R.layout.pop_lay, null, false);
final PopupWindow popWindow=new PopupWindow(view1, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
popWindow.setFocusable(true);
view1.setOnTouchListener(new OnTouchListener() {
@Override//这里主要是实现popwindow点击textview之外的地方会消失
public boolean onTouch(View view, MotionEvent event) {
int height = view1.findViewById(R.id.lay_pop).getTop();
int bottom=view1.findViewById(R.id.lay_pop).getBottom();
int y=(int) event.getY();
if(event.getAction()==MotionEvent.ACTION_UP){
if(y>height||y<bottom){
popWindow.dismiss();
}
}
return false;
}
} ) ;
TextView tv_pop=(TextView) view1.findViewById(R.id.tv_pop);
tv_pop.setText(content);
return popWindow;
}
}
使用:
PopWindowUtils.getMyPopWindow(MainActivity.this, "zailus").showAtLocation(findViewById(R.id.button1), Gravity.CENTER, 0, 0);
其中findViewById(R.id.button1)为出发点击的按钮
是否是很简单呢