最近作項目時,遇到一種狀況,請求服務器時,要把結果提示給用戶,但是因爲網絡緣由,反應不是很靈敏,用戶就會屢次點擊一個或惡意連着快速點擊多個能夠出發提示的按鈕,這時,就會連着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)爲出發點擊的按鈕
是否是很簡單呢