一开始在项目中用到弹出的AlertDialog,发现需求中的AlertDialog的背景透明且是左边不显示,右边显示出来。自己想这用Dialog可以实现吧!但是尝试了很久没有实现出来。自己决定用PopupWindow,最后解决了。使用AlertDialog没有实现也许是自己的技术不行吧!
1.自定义的PopupWindow
public class MyPopupWindow extends PopupWindow {
private TextView mTvP_Number;
private View mView;
public MyPopupWindow(){
super();
}
public MyPopupWindow(Context context,AttributeSet attr){
super(context,attr);
}
public MyPopupWindow(final Context context){
setWidth(LayoutParams.MATCH_PARENT);
setHeight(LayoutParams.MATCH_PARENT);
setFocusable(true);
setTouchable(true);
setOutsideTouchable(false);
setBackgroundDrawable(new BitmapDrawable());
setTouchInterceptor(new OnTouchListener()
@Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_OUTSIDE){
dismiss();
return true;
}
return false;
}
});
}
public void addView(View mview){
this.mView=mview;
setContentView(this.mView);
}
public void setMessage(String msg,int id){
mTvP_Number=(TextView)this.mView.findViewById(id);
mTvP_Number.setText(msg);
}
public void setSpanned(Spanned msg,int id){
mTvP_Number=(TextView)this.mView.findViewById(id);
mTvP_Number.setText(msg);
}
}
首先解释下为什么这样自定义MyPopupWindow?是为了适应不同的xml布局,这样只要在MainActivity中获得View view=LayoutInflater.from(this).inflater(xxx,xxx);直接把view传到 addView(View view)方法中就可以了,非常方便!
setTouchInterceptor()方法中if()内容是为了再点击非PopupWindow区域会触发。
2.下面是一个PopupWindow中的布局
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/wbg"
android:gravity="center_vertical|center_horizontal">
<LinearLayout
android:layout_width="350dp"
android:layout_height="250dp"
android:orientation="vertical"
android:background="@drawable/dialog_shape"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="取号成功!"
android:background="@color/transparent"
android:layout_marginTop="40dp"
android:textColor="#EEEEEEEE"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:textSize="20sp"
android:background="@color/transparent"
android:textColor="#EEEEEEEE"
android:text="请告知客户票号为:"/>
<TextView
android:id="@+id/tvp_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="R05"
android:textSize="30sp"
android:background="@color/transparent"
android:textColor="#EE950C"/>
</LinearLayout>
</LinearLayout>
下面是values文件下的colors.xml中的
<color name="br">#979797</color>
<color name="wbg">#40404040</color>
这个布局文件就不解释了
3.最后在mainActivity中调用PopupWindow显示的位置
myPopupWindow.showAtLocation(myPopupView,Gravity.CLIP_VERTICAL|Gravity.CLIP_HORIZONTAL,420,0);
这段代码可以控制背景显示的位置!
最后希望这个小小的案例可以帮到大家!我也是一个小菜鸟!