1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.car.settings.common.rotary; 18 19 import android.view.KeyEvent; 20 import android.view.View; 21 import android.widget.NumberPicker; 22 23 import java.util.Map; 24 25 /** 26 * A nudge handler to deal with {@link NumberPicker} instances. Ensures that nudging keeps focus 27 * within the parent container of the {@link NumberPicker}. 28 */ 29 public class NumberPickerNudgeHandler implements View.OnKeyListener { 30 31 private static final Map<Integer, Integer> KEYCODE_TO_DIRECTION_MAP = Map.of( 32 KeyEvent.KEYCODE_DPAD_UP, View.FOCUS_UP, 33 KeyEvent.KEYCODE_DPAD_DOWN, View.FOCUS_DOWN, 34 KeyEvent.KEYCODE_DPAD_LEFT, View.FOCUS_LEFT, 35 KeyEvent.KEYCODE_DPAD_RIGHT, View.FOCUS_RIGHT); 36 37 @Override onKey(View view, int keyCode, KeyEvent event)38 public boolean onKey(View view, int keyCode, KeyEvent event) { 39 switch (keyCode) { 40 case KeyEvent.KEYCODE_DPAD_UP: 41 case KeyEvent.KEYCODE_DPAD_DOWN: 42 // Disable by consuming the event and not doing anything. 43 return true; 44 case KeyEvent.KEYCODE_DPAD_LEFT: 45 case KeyEvent.KEYCODE_DPAD_RIGHT: 46 if (event.getAction() == KeyEvent.ACTION_UP) { 47 int direction = KEYCODE_TO_DIRECTION_MAP.get(keyCode); 48 View nextView = view.focusSearch(direction); 49 if (NumberPickerUtils.hasCommonNumberPickerParent(view, nextView)) { 50 nextView.requestFocus(direction); 51 } 52 } 53 return true; 54 default: 55 return false; 56 } 57 } 58 } 59