NumberPicker:函数onFocusChange从未调用过

时间:2016-03-18 14:54:16

标签: java android

onFocusChange没有被调用。 我用这个创建了一个新项目,它无法正常工作。 这是代码:

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。

1 个答案:

答案 0 :(得分: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>