๊ด€๋ฆฌ ๋ฉ”๋‰ด

Welcome! Everything is fine.

[Android] ํ‚ค๋ณด๋“œ๊ฐ€ ๋‘๋ฒˆ ๋ˆŒ๋ฆฌ๋Š” ์˜ค๋ฅ˜(setOnKeyListener) ๋ณธ๋ฌธ

Android

[Android] ํ‚ค๋ณด๋“œ๊ฐ€ ๋‘๋ฒˆ ๋ˆŒ๋ฆฌ๋Š” ์˜ค๋ฅ˜(setOnKeyListener)

๊ฐœ๋ฐœ๊ณฐ๋ฐœ 2023. 9. 14.
728x90

๐Ÿ“Œ ๋ฌธ์ œ

ํ™”๋ฉด ์ƒ๋‹จ์˜ ๊ฒ€์ƒ‰ ๋ฒ„ํŠผ๊ณผ ํ‚ค๋ณด๋“œ์˜ ๊ฒ€์ƒ‰ ๋ฒ„ํŠผ์ด ๋ˆŒ๋ ธ์„ ๋•Œ์˜ ๋ฐ˜์‘์ด ๋‹ค๋ฅธ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์—ˆ๋‹ค. ์ƒ๋‹จ์˜ ๊ฒ€์ƒ‰ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ์ •์ƒ์ ์œผ๋กœ ํ•œ ๊ฐœ์˜ ๊ณ„์ •๋งŒ ๋‚˜์˜ค์ง€๋งŒ, ํ‚ค๋ณด๋“œ์˜ ๊ฒ€์ƒ‰ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ๋˜‘๊ฐ™์€ ๊ณ„์ •์ด ๋‘ ๋ฒˆ ์ถœ๋ ฅ๋˜๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค.

ํ‚ค๋ณด๋“œ ์—”ํ„ฐํ‚ค(๋‹๋ณด๊ธฐ ๋ชจ์–‘)๋ฅผ ๋ˆŒ๋ €์„ ์‹œ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ

๐Ÿ“Œ ํ•ด๊ฒฐ

ํ† ์ŠคํŠธ ๋ฉ”์‹œ์ง€๋กœ ํ™•์ธํ•ด๋ณด๋‹ˆ onKey() ๋ฉ”์„œ๋“œ๊ฐ€ ๋‘ ๋ฒˆ ์‹คํ–‰๋˜๊ณ  ์žˆ์—ˆ๋‹ค. ์ฐพ์•„๋ณด๋‹ˆ ํ‚ค๋ณด๋“œ์—์„œ ์—”ํ„ฐํ‚ค๋ฅผ ๋ˆ„๋ฅด๋ฉด ACTION_UP๊ณผ ACTION_DOWN, ์ด 2๋ฒˆ์˜ ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ•˜๋”” ๋•Œ๋ฌธ์ด๋ผ๊ณ  ํ•œ๋‹ค. ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์•„๋ž˜ ์ฒซ ๋ฒˆ์งธ ์ฝ”๋“œ์™€ ๊ฐ™์ด ๋‹จ์ˆœํžˆ ์—”ํ„ฐํ‚ค๊ฐ€ ๋ˆŒ๋ ธ์„ ๋•Œ๋งŒ์„ ์กฐ๊ฑด์œผ๋กœ ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋‘ ๋ฒˆ์งธ ์ฝ”๋“œ์™€ ๊ฐ™์ด ACTION_UP๊ณผ ACTION_DOWN ์ค‘ ํ•˜๋‚˜๋งŒ ์„ ํƒํ•˜์—ฌ ์กฐ๊ฑด์„ ๋‹ฌ์•„์ค˜์•ผ ํ•œ๋‹ค. 

searchEditText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            searchBtn.performClick();
            hideKeyboard();
        }
        return false;
    }
});

 

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•œ ๊ฒฐ๊ณผ, ํ‚ค๋ณด๋“œ ์—”ํ„ฐํ‚ค๋กœ ๊ฒ€์ƒ‰์œผ๋กœ ํ•ด๋„ ์ค‘๋ณต์œผ๋กœ ๋‚˜์˜ค์ง€ ์•Š๊ณ  ์ •์ƒ์ ์œผ๋กœ ์ถœ๋ ฅ๋˜์—ˆ๋‹ค.

searchEditText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER 
        && keyEvent.getAction() == KeyEvent.ACTION_UP) {
            searchBtn.performClick();
            hideKeyboard();
        }
        return false;
    }
});