PopupWindow的简单使用

来源:互联网 发布:word转换成excel软件 编辑:程序博客网 时间:2024/05/22 14:27

    PopupWindow是一个弹框的效果,他可以在点击某一个控件的时候弹出一个信息。

    它得使用两个布局来实现,一个是父布局,另一个是需要弹出的布局。


     废话不多说,直接上代码

两个布局:

1、

<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" tools:context="niuwei.com.popwindowdemo.MainActivity">    <Button        android:layout_centerVertical="true"        android:id="@+id/bt_login"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="登录" /></RelativeLayout>

2、
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    >    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="我是PopupWindow"        android:textSize="30sp"        android:textColor="#f00"        android:gravity="center_horizontal"        /></LinearLayout>


Activity代码:

public class MainActivity extends AppCompatActivity {    private View parent;    private View child;    private PopupWindow popupWindow;    private Button bt;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        bt = (Button) findViewById(R.id.bt_login);        //把布局转化成视图        parent = View.inflate(this, R.layout.activity_main,null);        child = View.inflate(this, R.layout.pop_layout,null);        popupWindow = new PopupWindow(child, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);        //设置外部空白区域是否可以触摸        popupWindow.setOutsideTouchable(true);        /**         *  下面的方法要结合着 设置背景去用 new BitmapDrawable()意思是一个空的背景         *  两个方法结合使用 可以使点击周围的时候 窗体消失 ;点击返回键的时候窗体消失 而不是直接作用在activity上         */        popupWindow.setBackgroundDrawable(new BitmapDrawable());        //点击popupWindown让其消失        popupWindow.setTouchable(true);        child.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                popupWindow.dismiss();            }        });        //popupWindow的显示有三种简单方式        bt.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                 popupWindow.showAsDropDown(bt);//显示在传入控件的左下方,并且没有偏移                // popupWindow.showAsDropDown(bt, 40,30);                // 显示在传入控件的左下方,并且有偏移                //popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);            }        });    }}


原创粉丝点击