2016-03-18 112 views
0

onFocusChange不會被調用。 我用這個創建了一個新項目,它不起作用。 下面是代碼:NumberPicker:function onFocusChange never called

private NumberPicker np; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    np = (NumberPicker)findViewById(R.id.numberPicker1); 
    np.setMaxValue(99); 
    np.setMinValue(0); 
    np.setValue(50); 

    np.setOnFocusChangeListener(new View.OnFocusChangeListener() { 
     @Override 
     public void onFocusChange(View v, boolean hasFocus) { 
      Log.d(TAG, "np hasFocus " + hasFocus); 
     } 
    }); 
} 

和XML:

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"> 

    <NumberPicker 
     android:id="@+id/numberPicker1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     android:focusable="true" 
     android:focusableInTouchMode="true" 
     > 
    </NumberPicker> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:text="test button" 
     /> 
</LinearLayout> 

可以請你發生了什麼幫助? 我使用的是Android 4.4.2,API 19

+0

我看到有一個[onValueChangeListerner](http://developer.android.com/intl/zh-tw/reference/android/widget/NumberPicker.OnValueChangeListener.html) –

+0

@Uma Kanth謝謝,但我真正想要的是onFocusChange ... –

回答

0

擴展NumberPicker類工作對我來說:

public class MyNumberPicker extends android.widget.NumberPicker { 
    private final String TAG = MyNumberPicker.class.getSimpleName(); 
    View.OnFocusChangeListener mOnFocusChangeListener; 

    public MyNumberPicker(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    public void setOnFocusChangeListener(View.OnFocusChangeListener listener){ 
     mOnFocusChangeListener = listener; 
    } 

    @Override 
    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { 
     Log.d(TAG,"onFocusChanged called by the view system"); 
     super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); 
     if (mOnFocusChangeListener != null) { 
      mOnFocusChangeListener.onFocusChange(this, gainFocus); 
     } 
    } 
} 

,並在XML只是使用類似:

<com.example.npicktest.MyNumberPicker 
     android:id="@+id/myNumberPicker1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     android:focusable="true" 
     android:focusableInTouchMode="true" 
     > 
    </com.example.npicktest.MyNumberPicker>