Android UI自定义Spinner下拉框(用popuwindow实现)
16lz
2021-01-23
首页 » Android » Android UI自定义Spinner下拉框(用popuwindow实现)
Android UI自定义Spinner下拉框(用popuwindow实现)
日期: 2013-09-27作者: 梁 捷分类: Android评论: 0
01 | @Override |
02 | protected void onCreate(Bundle savedInstanceState) { |
03 | super .onCreate(savedInstanceState); |
04 | setContentView(R.layout.activity_main); |
05 | textView = (TextView) findViewById(R.id.text); |
06 | imgView = findViewById(R.id.arrowbut); |
07 | // 实例化一个List,添加数据 |
08 | list = new ArrayList |
09 | list.add( "第一展厅" ); |
10 | list.add( "第二展厅" ); |
11 | list.add( "第三展厅" ); |
12 | // 实例化一个适配器,list的数据作为Adapter的数据 |
13 | adapter = new MyspinnerAdapter( this , list); |
14 | // 默认设置下拉框的标题为数据的第一个 |
15 | textView.setText((CharSequence) adapter.getItem( 0 )); |
16 | spinnerlayout = (LinearLayout) findViewById(R.id.spinnerid); |
17 | // 点击右侧按钮,弹出下拉框 |
18 | imgView.setOnClickListener( new OnClickListener() { |
19 |
20 | @Override |
21 | public void onClick(View v) { |
22 |
23 | showWindow(v); |
24 |
25 | } |
26 | }); |
27 | } |
28 |
29 | @SuppressWarnings ( "deprecation" ) |
30 | public void showWindow(View v) { |
31 | // 找到布局文件 |
32 | layout = (LinearLayout) LayoutInflater.from( this ).inflate(R.layout.mypinner_dropdown, null ); |
33 | // 实例化listView |
34 | listView = (ListView) layout.findViewById(R.id.listView); |
35 | // 设置listView的适配器 |
36 | listView.setAdapter(adapter); |
37 | // 实例化一个PopuWindow对象 |
38 | popupWindow = new PopupWindow(v); |
39 | // 设置弹框的宽度为布局文件的宽 |
40 | popupWindow.setWidth(spinnerlayout.getWidth()); |
41 | // 高度随着内容变化 |
42 | popupWindow.setHeight(LayoutParams.WRAP_CONTENT); |
43 | // 设置一个透明的背景,不然无法实现点击弹框外,弹框消失 |
44 | popupWindow.setBackgroundDrawable( new BitmapDrawable()); |
45 | // 设置点击弹框外部,弹框消失 |
46 | popupWindow.setOutsideTouchable( true ); |
47 | // 设置焦点 |
48 | popupWindow.setFocusable( true ); |
49 | // 设置所在布局 |
50 | popupWindow.setContentView(layout); |
51 | // 设置弹框出现的位置,在v的正下方横轴偏移textview的宽度,为了对齐~纵轴不偏移 |
52 | popupWindow.showAsDropDown(v, -textView.getWidth(), 0 ); |
53 | // listView的item点击事件 |
54 | listView.setOnItemClickListener( new OnItemClickListener() { |
55 |
56 | @Override |
57 | public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { |
58 | // TODO Auto-generated method stub |
59 | textView.setText(list.get(arg2)); // 设置所选的item作为下拉框的标题 |
60 | // 弹框消失 |
61 | popupWindow.dismiss(); |
62 | popupWindow = null ; |
63 | } |
64 | }); |
65 |
66 | } |
1 | https://github.com/liangjie0521/TestSpinner2.git |
更多相关文章
- Android系列之Android开发教程代码实例
- 自定义SeekBarPreference控件(老外出品,直接在preferences文件中
- android实现自定义相机以及图片的水印
- Android基础控件——ProgressBar自定义的介绍、动画效果实现、附
- Android DrawerLayout实现抽屉效果实例代码