1)通过扩展微调器创建一个自定义微调器类,
public class CCSpinner extends Spinner {
public CCSpinner(Context context) {
super(context);
}
public CCSpinner(Context context, int mode) {
super(context, mode);
}
public CCSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CCSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CCSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode) {
super(context, attrs, defStyleAttr, mode);
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
}
在您的 xml 视图中使用上述微调器。
2)定义一个接口来处理点击,
public interface ClickListener {
void onItemLongClicked(View view);
void onItemClicked(View view);
}
3) 在您的微调器适配器类中,在 getView 和 getDropDownView 中执行这些操作
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//ususal stuffs
convertView.setTag(R.string.click_tag, position);
convertView.setClickable(false);
convertView.setLongClickable(false);
return convertView;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
//ususal stuffs
convertView.setTag(R.string.click_tag, position);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (clickListener != null) {
clickListener.onItemClicked(v);
}
}
});
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (clickListener != null) {
clickListener.onItemLongClicked(v);
}
return true;
}
});
return convertView;
}
4) 在实例化适配器时,传递我们创建的 ClcikListener 接口。
5)并在实现类中执行以下操作,
@Override
public void onItemLongClicked(final View view) {
mPSpinner.onDetachedFromWindow();
final int pos = (int) view.getTag(R.string.click);
mPSpinner.setSelection(pos);
}
@Override
public void onItemClicked(final View view) {
mPSpinner.onDetachedFromWindow();
int pos = (int) view.getTag(R.string.click);
mPSpinner.setSelection(pos);
}