2010-11-22 34 views
2

我在表单活动中遇到了spinners问题。spinners and focus

我曾期待一位微调员在用户“触摸”它时获得焦点,但这似乎并没有发生。如果我使用我的跟踪球(在Nexus One上)在不同组件之间移动,那么微调似乎只能获得关注。

这很烦人,因为我在窗体的第一个EditText视图中使用了android:selectAllOnFocus =“true”属性。因为spinners从未将注意力从EditText组件中移除,所以它的内容总是被高亮显示(这是丑陋的IMO)。

我使用

spinner.requestFocus();

尝试,但这个(貌似)没有任何影响。

我试过要求注重微调在AdapterView.OnItemSelectedListener但他只是导致

Window already focused, ignoring focus gain of: [email protected]

谁能解释这个奇怪的行为和/或周围可能的方式。

非常感谢,

+0

我在表单中有相同的行为,但我的表单因为某种原因运行,每当我从微调框中选择一些内容时,我都会收到此警告。 – JPM 2011-10-13 16:58:02

回答

1

你必须首先使用setFocusableInTouchMode()。然后你遇到一个不同的问题:你必须点击微调器两次来改变它(一次设置焦点,然后再次看到选项列表)。我的解决方案是创建自己的微调子类,可使从第一点触对焦增益模拟第二:

class MySpinnerSubclass extends Spinner { 

    private final OnFocusChangeListener clickOnFocus = new OnFocusChangeListener() { 

     @Override 
     public void onFocusChange(View v, boolean hasFocus) { 

      // We don't want focusing the spinner with the d-pad to expand it in 
      // the future, so remove this listener until the next touch event. 
      setOnFocusChangeListener(null); 
      performClick(); 
     } 
    }; 

    // Add whatever constructor(s) you need. Call 
    // setFocusableInTouchMode(true) in them. 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 

     int action = event.getAction(); 
     if (action == MotionEvent.ACTION_DOWN) { 

      // Only register the listener if the spinner does not already have 
      // focus, otherwise tapping it would leave the listener attached. 
      if (!hasFocus()) { 
       setOnFocusChangeListener(clickOnFocus); 
      } 
     } else if (action == MotionEvent.ACTION_CANCEL) { 
      setOnFocusChangeListener(null); 
     } 
     return super.onTouchEvent(event); 
    } 
} 

要给予适当的信贷,我得到了我的灵感来自Kaptkaos's answerthis question