我使用带游标适配器的下拉微调器。它包含例如1到100个项目。 我选择例如项目50.项目已被选中。下次当我打开微调器时,第一个可见行是第50项。当我打开微调器时,我将如何实现它将聚焦到第一个项目/第一个可见项目将是第1项?
我的意思是在列表中自动滚动,因此下拉列表中的第一个可见项目是第一个,而不是一个。
答案 0 :(得分:35)
您可以通过扩展Spinner
来执行您想要的操作,并覆盖负责设置/显示值列表的两种方法:
public class CustomSpinnerSelection extends Spinner {
private boolean mToggleFlag = true;
public CustomSpinnerSelection(Context context, AttributeSet attrs,
int defStyle, int mode) {
super(context, attrs, defStyle, mode);
}
public CustomSpinnerSelection(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public CustomSpinnerSelection(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSpinnerSelection(Context context, int mode) {
super(context, mode);
}
public CustomSpinnerSelection(Context context) {
super(context);
}
@Override
public int getSelectedItemPosition() {
// this toggle is required because this method will get called in other
// places too, the most important being called for the
// OnItemSelectedListener
if (!mToggleFlag) {
return 0; // get us to the first element
}
return super.getSelectedItemPosition();
}
@Override
public boolean performClick() {
// this method shows the list of elements from which to select one.
// we have to make the getSelectedItemPosition to return 0 so you can
// fool the Spinner and let it think that the selected item is the first
// element
mToggleFlag = false;
boolean result = super.performClick();
mToggleFlag = true;
return result;
}
}
它应该适合您想要做的事情。
答案 1 :(得分:2)
您可以将Spinner的选择设置为第一项,如下所示:
yourspinner.setSelection(0);
您可能希望在onStart()方法中执行此操作。
答案 2 :(得分:1)
这段代码将为您完成工作。
int prevSelection=0;
spSunFrom = (Spinner) findViewById(R.id.spTimeFromSun);
spSunFrom.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
prevSelection = spSunFrom.getSelectedItemPosition();
spSunFrom.setSelection(0);
return false;
}
});
spSunFrom.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if(arg2==0)
spSunFrom.setSelection(prevSelection);
prevSelection = arg2;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
spSunFrom.setSelection(prevSelection);
}
});