效果
PopWinLayout
package com.coral3.common_module.components;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import androidx.annotation.Nullable;
import com.coral3.common_module.R;
import com.coral3.common_module.adapter.PopWindowAdapter;
import com.coral3.common_module.model.PopModel;
import java.util.ArrayList;
import java.util.List;
public class PopWinLayout extends LinearLayout {
private Context mContext;
private ListView lv;
private ImageView asDropDownView;
private PopupWindow window;
private List data = new ArrayList<>();
private View view;
public PopWinLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
initView();
initLocalData();
initPop();
}
private void initView(){
view = LayoutInflater.from(mContext).inflate(R.layout.layout_pop_window, this);
}
private void initLocalData(){
data.add(new PopModel(R.mipmap.msg, "发起群聊"));
data.add(new PopModel(R.mipmap.msg, "添加好友"));
data.add(new PopModel(R.mipmap.msg, "扫一扫"));
data.add(new PopModel(R.mipmap.msg, "收付款"));
data.add(new PopModel(R.mipmap.msg, "帮助与反馈"));
}
private void initPop(){
//获取其中的ListView
lv = view.findViewById(R.id.lv_pop_list);
//设置适配
PopWindowAdapter adapter = new PopWindowAdapter(mContext, R.layout.custom_spinner_dropdown_item, data);
lv.setAdapter(adapter);
//创建PopupWindow对象
window = new PopupWindow(this);
//给PopupWindow设置一个View
window.setContentView(view);
//设置宽和高
window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
window.setWidth(333);
//点击窗口意外 窗口消失
window.setOutsideTouchable(true);
}
public void setDropDownBtn(ImageView v){
asDropDownView = v;
}
public void showPopView(){
//显示在某个控件的下方
if(null != asDropDownView) window.showAsDropDown(asDropDownView, -203, 50);
}
public void hidePopView(){
//显示在某个控件的下方
if(null != asDropDownView) window.dismiss();
}
}