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.HashMap; 24 import java.util.Map; 25 26 /** 27 * A nudge handler to deal with {@link NumberPicker} instances. Ensures that nudging keeps focus 28 * within the parent container of the {@link NumberPicker}. 29 */ 30 public class NumberPickerNudgeHandler implements View.OnKeyListener { 31 32 private static final Map<Integer, Integer> KEYCODE_TO_DIRECTION_MAP = 33 new HashMap<Integer, Integer>() {{ 34 put(KeyEvent.KEYCODE_DPAD_UP, View.FOCUS_UP); 35 put(KeyEvent.KEYCODE_DPAD_DOWN, View.FOCUS_DOWN); 36 put(KeyEvent.KEYCODE_DPAD_LEFT, View.FOCUS_LEFT); 37 put(KeyEvent.KEYCODE_DPAD_RIGHT, View.FOCUS_RIGHT); 38 }}; 39 40 @Override onKey(View view, int keyCode, KeyEvent event)41 public boolean onKey(View view, int keyCode, KeyEvent event) { 42 switch (keyCode) { 43 case KeyEvent.KEYCODE_DPAD_UP: 44 case KeyEvent.KEYCODE_DPAD_DOWN: 45 // Disable by consuming the event and not doing anything. 46 return true; 47 case KeyEvent.KEYCODE_DPAD_LEFT: 48 case KeyEvent.KEYCODE_DPAD_RIGHT: 49 if (event.getAction() == KeyEvent.ACTION_UP) { 50 int direction = KEYCODE_TO_DIRECTION_MAP.get(keyCode); 51 View nextView = view.focusSearch(direction); 52 if (NumberPickerUtils.hasCommonNumberPickerParent(view, nextView)) { 53 nextView.requestFocus(direction); 54 } 55 } 56 return true; 57 default: 58 return false; 59 } 60 } 61 } 62