欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spinner的实现

程序员文章站 2022-07-04 16:22:33
...

1.dropdowm mode:

使用的是ListPopupWindow:

设置ListPopupWindow的ListView的OnItemClickListener:

public DropdownPopup(
                Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);

            setAnchorView(Spinner.this);
            setModal(true);
            setPromptPosition(POSITION_PROMPT_ABOVE);
            setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View v, int position, long id) {//调用该方法后,requestLayout(),重新布局将调用Spinner的layout()方法,方法中将根据position,把selected item的view从ListView中取出,addView到Spinner中。因为执行layout时,该List View已经从PupupWindow中解绑,窗口也移除了。Spinner算是废物利用,但是不明白的是,为什么PopupWindow用一次ListView就不用了。
                    Spinner.this.setSelection(position);
                    if (mOnItemClickListener != null) {
                        Spinner.this.performItemClick(v, position, mAdapter.getItemId(position));//调用Spinner.setOnItemClickListener设置的
                    }
                    dismiss();//wm.removeView()
                }
            });
        }

2.dialogMode:

使用的是AlertDialog的singleIchoice样式的ListView。

        public void show(int textDirection, int textAlignment) {
            if (mListAdapter == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getPopupContext());
            if (mPrompt != null) {
                builder.setTitle(mPrompt);
            }
            mPopup = builder.setSingleChoiceItems(mListAdapter,
                    getSelectedItemPosition(), this).create();
            final ListView listView = mPopup.getListView();
            listView.setTextDirection(textDirection);
            listView.setTextAlignment(textAlignment);
            mPopup.show();
        }

        public void onClick(DialogInterface dialog, int which) {//该类实现了DialogInterface.OnClickListener
            setSelection(which);
            if (mOnItemClickListener != null) {
                performItemClick(null, which, mListAdapter.getItemId(which));
            }
            dismiss();
        }