Dialog实现Spinner下拉列表效果

时间:2021-10-27 12:42:42

Dialog实现Spinner下拉列表效果

    Dialog实现Spinner下拉列表效果

先看下效果,我感觉比Spinner效果要好些,记录下实现过程。

    

final String[] levelArray = getResources().getStringArray(R.array.contact_level);
re_layout_spinner.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!isExpand) {
dialog = new Dialog(mSelf);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
ListView mListView = new ListView(mSelf);
mListView.setCacheColorHint(Color.TRANSPARENT);
mListView.setAdapter(new LevelAdapter());
mListView.setBackgroundResource(R.drawable.information_blue_bg);
mListView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
tv_level.setText(levelArray[position]);
if (dialog != null) {
dialog.dismiss();
dialog = null;
isExpand = false;
}
}
});
dialog.setContentView(mListView);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
isExpand = false;
}
});
Window dialogWindow = dialog.getWindow();
dialogWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.RED));
dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.dimAmount = 0f;
int[] location = new int[2];
re_layout_spinner.getLocationOnScreen(location);
Rect out = new Rect();
re_layout_spinner.getWindowVisibleDisplayFrame(out);
lp.x = location[0];
lp.y = location[1] - out.top + re_layout_spinner.getHeight();
lp.width = re_layout_spinner.getWidth();
lp.height = LayoutParams.WRAP_CONTENT;
dialogWindow.setAttributes(lp);
dialog.show();
isExpand = true;
} else {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
}
});

new LevelAdapter()中就放了一个TextView,其他需要说下的是Dialog弹出位置的设定,我想让它贴着我的RelativeLayout出现就要获取这个RelativeLayout的位置,而re_layout_spinner.getLocationOnScreen(location);获取的是距离屏幕顶端的位置,所以还要获取状态栏的高度,减去这个高度才可以正确显示在我们需要的位置。