效果图
1:布局文件中声明布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.joker.popuwindow.MainActivity">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="wrap_content">
<EditText
android:id="@+id/et_input"
android:singleLine="true"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/ib_down_arrow"
android:layout_alignParentRight="true"
android:src="@drawable/down_arrow"
android:background="@null"
android:paddingBottom="6dp"
android:layout_width="wrap_content"
android:layout_height="35dp"
/>
</RelativeLayout>
</RelativeLayout>
2:准备数据,准备ListView
// 初始化要显示的内容
private void initListView() {
listView = new ListView(this);
listView.setDividerHeight(0);
listView.setBackgroundResource(R.drawable.listview_background);
listView.setOnItemClickListener(this);
datas = new ArrayList<String>();
// 创建一些数据
for (int i = 0; i < 30; i++) {
datas.add((10000 + i) + "");
}
listView.setAdapter(new MyAdapter());
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
System.out.println("onItemClick: " + position);
String string = datas.get(position);
et_input.setText(string); // 设置文本
popupWindow.dismiss(); // 消失了
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return datas.size();
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
view = View.inflate(parent.getContext(), R.layout.item_number, null);
}else {
view = convertView;
}
TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
tv_number.setText(datas.get(position));
view.findViewById(R.id.ib_delete).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datas.remove(position);
notifyDataSetChanged();
if(datas.size() == 0){
// 如果删除的是最后一条, 隐藏popupwindow
popupWindow.dismiss();
}
}
});
return view;
}
}
3:创建showPopupWindow方法
private void showPopupWindow() {
initListView();
// 显示下拉选择框(放入的控件,宽,高)
popupWindow = new PopupWindow(listView, et_input.getWidth(), 300);
// 设置点击外部区域, 自动隐藏
popupWindow.setOutsideTouchable(true); // 外部可触摸
popupWindow.setBackgroundDrawable(new BitmapDrawable()); // 设置空的背景, 响应点击事件
popupWindow.setFocusable(true); //设置可获取焦点
// 显示在指定控件下
popupWindow.showAsDropDown(et_input, 0, -5);
}