概述
常用的弹窗有菜单,或者Dialog,但更加人性化和可自定义的还是PopupWindow 如果只是展示列表数据或者弹窗列表选择,直接使用ListPopupWindow即可,不用再单独去设置布局。 如果想要更加多样化的那就自定义一个布局,使用PopupWindow即可,也不复杂。
用法
自定义ListPopupWindow类
public class ChargeItemSumPop extends ListPopupWindow {
public ChargeItemSumPop(Context context) {
super(context);
}
}
属性设置
因为里面已经有一个列表控件了,所以,不用再绑定布局
setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
setWidth(600);
setModal(true);
setBackgroundDrawable(new ColorDrawable(0xCC000000));
绑定Adapter
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
List<Integer> lstYear = new ArrayList<>();
for(int i = 2015; i <= year; i++){
lstYear.add(i);
}
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, lstYear);
setAdapter(adapter);
Activity监听
ChargeDateYearPop pop = new ChargeDateYearPop(this);
pop.setOnItemClickListener((adapterView, view, i, l) -> {
bindingView.chargeYear.setText(String.valueOf(adapterView.getAdapter().getItem(i)));
pop.dismiss();
});
pop.setAnchorView(bindingView.chargeYear);
pop.show();
完整弹窗类
与普通的弹窗不一样的地方在于这里面是一个列表,所以要绑定Adapter进行展示
public class ChargeDateYearPop extends ListPopupWindow {
public ChargeDateYearPop(Context context) {
super(context);
setHeight(800);
setWidth(200);
setModal(true);
setBackgroundDrawable(new ColorDrawable(0xCC000000));
initView(context);
}
private void initView(Context context) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
List<Integer> lstYear = new ArrayList<>();
for(int i = 2015; i <= year; i++){
lstYear.add(i);
}
Collections.sort(lstYear);
Collections.reverse(lstYear);
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, lstYear);
setAdapter(adapter);
}
}
Activity
private void showChargeDateYear(){
ChargeDateYearPop pop = new ChargeDateYearPop(this);
pop.setOnItemClickListener((adapterView, view, i, l) -> {
bindingView.chargeYear.setText(String.valueOf(adapterView.getAdapter().getItem(i)));
pop.dismiss();
});
pop.setAnchorView(bindingView.chargeYear);
pop.show();
}
|