Android : PopupWindow 悬浮框_简单应用

示例图:

Android : PopupWindow 悬浮框_简单应用_第1张图片

MainActivity.java

package com.example.popupwindow;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    //组件
    protected Button button;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context =this;
        button = findViewById(R.id.btn_start);
        //事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPopupWindow(v);
            }
        });

    }

    private  void setPopupWindow(View v){
        //获取布局
        View view = LayoutInflater.from(context).inflate(R.layout.popupwindow_layout,null,false);
        Button butTit = view.findViewById(R.id.btn_tit);
        Button btnClose = view.findViewById(R.id.btn_close);

        // 创建一个 PopupWindow (视图,宽度,高度,焦点)
        //ViewGroup.LayoutParams.WRAP_CONTENT 自适应内容
        // true 可以弹出
         PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);


        //设置可以消失
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // true ,touch 事件会被拦截, onTouchEvent不会被调用,点击外面区域不能被关闭
                return false;
            }
        });
        //设置背景颜色
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xff00ff00));

        //设置popupWindow 视图弹出位置
        popupWindow.showAsDropDown(v,200,0);

        //按钮点击事件
        butTit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context,"点击了温馨提示",Toast.LENGTH_SHORT).show();
            }
        });

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //消失的方法
                popupWindow.dismiss();
            }
        });

    }

}

主布局 activity_main.xml




    

弹出框布局 popupwindow_layout.xml




    

你可能感兴趣的:(Android,相关,android)