Android PopupWindow的基本使用。

项目中有如下图的弹出框效果:
Android PopupWindow的基本使用。_第1张图片
这种效果用Popuwindow 就可以实现,具体代码如下。

package com.bjttsf.sale.widget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.bjttsf.sale.R;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

public class DetailPopup extends PopupWindow {

    private final RecyclerView rv;
    private BaseQuickAdapter adapter;
    private Context mContext;
    private ClickListener mClickListener;
    private List lists;

    public interface ClickListener {
        void topClick(int position);
    }

    public void setOnTopListener(ClickListener click) {
        mClickListener = click;
    }

    public DetailPopup(Context context, List lists) {
        super(context);
        mContext = context;
        this.lists = lists;
        //透明背景
        setBackgroundDrawable(mContext.getDrawable(R.drawable.detail_pop_bg));
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        setOutsideTouchable(true);
        setFocusable(true);
        View contentView = LayoutInflater.from(context).inflate(R.layout.popup_detail,
                null, false);
        setContentView(contentView);
        rv = contentView.findViewById(R.id.rv_popup);
        //业务相关  
        setrv();
    }

    private void setrv() {
        adapter = new BaseQuickAdapter(R.layout.item_detail_popup, lists) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {

            }
        };
        rv.setLayoutManager(new LinearLayoutManager(mContext));
        rv.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            if (mClickListener != null)
                mClickListener.topClick(position);
            dismiss();
        });
    }
}

   

在Activity中调用:

  DetailPopup popup = new DetailPopup(mContext, listbean);
   popup.showAsDropDown(mLlRight, 0, -40);

popup.showAsDropDown(View anchor, int xoff, int yoff)这个方法可以设置popuwindow 的弹出位置。 x,y 代表对View anchor 左下角坐标的相对位移。
x为正代表右移,为负是左移。 y为正代表下移,为负代表上移。
默认位置popuwindow 的左上角对齐 anchor 的左下角。

你可能感兴趣的:(Android PopupWindow的基本使用。)