带点击事件的Spinner
最近有一个蛋疼的需求,在下拉框中,如果只有一个值,默认显示出来,有两个或者没有显示请选择,没有点击不弹框,但是要清空,两个点击开要移掉请选择字样的项
本来以为很简单,后来发现没有OnClickListener,没办法,重写了一个Spinner
public class CSIISpinner extends Spinner {
public CSIISpinner(Context context) {
super(context);
}
public CSIISpinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CSIISpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
private boolean isMoved = false;
private Point touchedPoint = new Point();
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN :
touchedPoint.x = x;
touchedPoint.y = y;
break;
case MotionEvent.ACTION_MOVE :
isMoved = true;
break;
case MotionEvent.ACTION_UP :
if (isMoved) {
// 从上向下滑动
if (y - touchedPoint.y > 20) {
}
// 从下向上滑动
else if (touchedPoint.y - y > 20) {
}
// 滑动幅度小时,当作点击事件
else {
onClick();
}
isMoved = false;
} else {
onClick();
}
break;
default :
break;
}
return true;
}
private void onClick() {
if (OnClickListener != null && isEnabled()) {
OnClickListener.onClick();
}
}
private OnClickListener OnClickListener;
/**
* 注册自定义的点击事件监听
*
* @param onClickMyListener
*/
public void setOnClickListener(OnClickListener OnClickListener) {
this.OnClickListener = OnClickListener;
}
/**
* 自定义点击事件监听.
*/
public interface OnClickListener {
public void onClick();
}
}
后来发现这个用起来确实可以实现,但是不足之处就是太繁琐了
调用如下
subadapter = new ArrayAdapter<SubAccount>(NoticeDepositDrawPreActivity.this,R.layout.spinner_simple_item,subAccountList);
subadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_subacno.setAdapter(subadapter);
spinner_subacno.setPrompt("--请选择分账号序号--");
spinner_subacno.setOnClickListener(new CSIISpinner.OnClickListener() {
//此处新增一部分逻辑控制分账序号显示
@Override
public void onClick() {
if(subAccountList.size()==1&&subAccountList.get(0).getFenAcctNo().contains("请选择分账号序号")){
Component.alertDialog(NoticeDepositDrawPreActivity.this, "该帐号下面没有分账号信息");
subAccountList.get(0).setFenAcctNo("");
subadapter.notifyDataSetChanged();
}else{
if(subAccountList.get(0).getFenAcctNo().contains("请选择分账号序号")){
subAccountList.remove(0);
}
if("".equals((subAccountList.get(0).getAvailBal()))){
tv_balance.setText("");
}else{
tv_balance.setText(subAccountList.get(0).getAvailBal()+ "元");
}
ubadapter.notifyDataSetChanged();
spinner_subacno.performClick();
}
}
});
spinner_subacno.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent,View view, int position, long id) {
tv_balance.setText(subAccountList.get(position).getAvailBal()+ "元");
if("".equals((subAccountList.get(position).getAvailBal()))){
tv_balance.setText("");
}else{
tv_balance.setText(subAccountList.get(position).getAvailBal()+ "元");
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
好烦,将就用吧,有时间研究研究重写Spinner的Adapter怎么写,应该能控制Adapter会更加合理