需求:要自定义一个popupwindow,里面有个listview,我要将listview点击的条目信息回传给activity,当然方法很多,我是通过自定义监听回传的方式。
popupwindow的代码:
public class CountryPopView extends PopupWindow {
private View conentView;
private Context mContext;
private ListView sortListView;
private SortAdapter adapter;
private ArrayList<String> mSourceList;
/**
* 根据拼音来排列ListView里面的数据类
*/
private PinyinComparator pinyinComparator;
public CountryPopView(final Activity context, ArrayList<String> sourceList) {
mSourceList = sourceList;
mContext = context;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
conentView = inflater.inflate(R.layout.country_item_pop, null);
int h = context.getWindowManager().getDefaultDisplay().getHeight();
int w = context.getWindowManager().getDefaultDisplay().getWidth();
// 设置SelectPicPopupWindow的View
this.setContentView(conentView);
// 设置SelectPicPopupWindow弹出窗体的宽
this.setWidth(w);
// 设置SelectPicPopupWindow弹出窗体的高
this.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
// 设置SelectPicPopupWindow弹出窗体可点击
this.setFocusable(true);
this.setOutsideTouchable(true);
// 刷新状态
this.update();
this.setBackgroundDrawable(new BitmapDrawable());
initViews();
}
private void initViews() {
sortListView = (ListView) conentView.findViewById(R.id.country_lvcountry);
sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//这里要利用adapter.getItem(position)来获取当前position所对应的对象
if (onItemClickListener != null) {
onItemClickListener.itemClick(adapter.getItem(position));
}
}
});
adapter = new SortAdapter(mContext, mSourceList);
sortListView.setAdapter(adapter);
}
/**
* 显示popupWindow
*
* @param parent
*/
public void showPopupWindow(View parent) {
if (!this.isShowing()) {
// 以下拉方式显示popupwindow
this.showAsDropDown(parent, parent.getLayoutParams().width / 2, 18);
} else {
this.dismiss();
}
}
OnItemClickListener onItemClickListener;
public void setOnitemClickListener(OnItemClickListener mOnItemClickListener) {
onItemClickListener = mOnItemClickListener;
}
public interface OnItemClickListener {
void itemClick(String country);
}
}
activity主要代码:
if (mCountryPopView == null) {
mCountryPopView = new CountryPopView(this, mSourceList);
}
if (!mCountryPopView.isShowing()) {
mCountryPopView.showPopupWindow(btn_get_account);
mCountryPopView.setOnitemClickListener(new CountryPopView.OnItemClickListener() {
@Override
public void itemClick(String country) {
tv_country.setText(country);
}
});
}