1.需求中使用Spinner,不允许有默认选中,在网上查了好多,有设置
spinner.setSelection(-1,true);
也有设置如下:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { /** * 设置item的字体颜色 */ if(isFrist){ isFrist=false; }else{ TextView textView= (TextView) view; textView.setTextColor(getResources().getColor(R.color.hei)); Toast.makeText(MainActivity.this,""+parent.getItemIdAtPosition(position),Toast.LENGTH_SHORT).show(); } } @Override public void onNothingSelected(AdapterView parent) { } });
但是spinner初始时会默认走setOnItemSelectedListener方法,并使得position==0;如上设置,虽然不会显示默认了,但是第一次点击却不能选中第0项,
只能在选取其他项后,才能再选择0项。
再看,下面的设置:给予设置默认为1,这是,spinner初始时不会走setOnItemSelectedListener方法了,但是他第一次点击不能选择第1项了。
spinner.setSelection(1,true); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { /** * 设置item的字体颜色 */ TextView textView= (TextView) view; textView.setTextColor(getResources().getColor(R.color.hei)); Toast.makeText(MainActivity.this,""+parent.getItemIdAtPosition(position),Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView parent) { } });
2.后采用的TextView加ListPopupWindow实现这个需求:
TextView textView2; private ListPopupWindow popupWindow; private Liststrings;
textView2= (TextView) findViewById(R.id.textView2); strings = new ArrayList(); strings.add("item1"); strings.add("item2"); strings.add("item3"); popupWindow = new ListPopupWindow(this); popupWindow.setAdapter(new ArrayAdapter (this,android.R.layout.simple_list_item_1,strings)); popupWindow.setAnchorView(textView2); popupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT); popupWindow.setModal(true); popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { textView2.setText(strings.get(position)); popupWindow.dismiss(); Toast.makeText(MainActivity.this,""+textView2.getText().toString(),Toast.LENGTH_SHORT).show(); } }); textView2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.show(); } });
3.实现效果:
左侧是TextView和ListPopupWindow实现效果,右侧是Spinner效果
下拉效果对比: