PopupWindow+ListView并实现点击事件

这篇文章简单记录下PopupWindow+ListView并实现点击事件的实现。

效果图

感觉没什么可说的,多少废话,直接上代码

代码

展示PopupWindow

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void showPopupWindow() {
View view = View.inflate(MainActivity.this, R.layout.popup_window, null);
mPopListView = (ListView) view.findViewById(R.id.pop_list_view);

PopupWindow popupWindow = new PopupWindow(view, DisplayUtils.dip2px(this, 150),
DisplayUtils.dip2px(this, 240), true);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.update();
popupWindow.showAsDropDown(mBtnShow, DisplayUtils.dip2px(this, 50), 15);
mListViewAdapter = new ListViewAdapter(this,mData,popupWindow);
mPopListView.setAdapter(mListViewAdapter);
}

ListView的Adapter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.tech.kevin.poplistviewdemo;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.List;

/**
* Created by Kevin on 2017/2/28.
* Blog:http://blog.csdn.net/student9128
* Description:
*/

public class ListViewAdapter extends BaseAdapter {
private Context mContext;
private List<String> mData;
private PopupWindow mPopupWindow;

public ListViewAdapter(Context context, List<String> data, PopupWindow popupWindow) {
mContext = context;
mData = data;
mPopupWindow = popupWindow;
}

@Override
public int getCount() {
return mData.size();
}

@Override
public Object getItem(int i) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.adapter_popup_list_view, null);
viewHolder = new ViewHolder();
viewHolder.mTextView = (TextView) convertView.findViewById(R.id.tv_item);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mTextView.setText(mData.get(position));
viewHolder.mTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ToastUtils.showToast(mContext, mData.get(position));//在此处进行点击事件
mPopupWindow.dismiss();
}
});
return convertView;
}

static class ViewHolder {
TextView mTextView;
}
}

布局就没啥可贴的了。

Demo下载