3

I want to display android keyboard when fragment starts.

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

I use this code and it works. But how to change the keyboard to numeric keyboard? number only. And how to listen to the keyboard event like "1" on keyboard is pressed?

Meng Tim
  • 258
  • 5
  • 18
  • Possible duplicate of [EditText with number keypad by default, but allowing alphabetic characters](http://stackoverflow.com/questions/3544214/edittext-with-number-keypad-by-default-but-allowing-alphabetic-characters) – Gavriel Jan 28 '16 at 22:37
  • Do you have an `EditText` to take input from the keyboard? – Sharj Jan 28 '16 at 22:40
  • Use inputType="number" for your edittext in your fragment. –  Jan 28 '16 at 22:49
  • @Sharj I do not have EditText. I want to use keyboard to update the interface. Like I have a image view. I want to do: When user click "1" on soft keyboard, then change the image in the image view. – Meng Tim Jan 28 '16 at 22:50
  • Probably buttons is better for that Or maybe you should use an EditText. –  Jan 28 '16 at 22:51
  • Are you find any way to display numeric keyboard default? – NovusMobile Aug 12 '16 at 12:03

2 Answers2

1

Hopping to help someone to get stuck in that this is my solution.

(even know that this is not the exact question I get in this page a lot of times because of the way that the question was made)

Based on this solution Soft Keyboard for Dialog and Activity I get answer to show the Numeric Keyboard inside a Fragment when open the Screen.

First you have to be sure that your element in .XML file is number type

android:inputType="number"

Then, inside your code you do this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fragmentView = super.onCreateView(inflater, container, savedInstanceState);
    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    return fragmentView;
}

And don't forget to focus your element, like this

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    myElement.requestFocus();
}
Canato
  • 2,116
  • 1
  • 25
  • 44
0

You'd need to create an InputConnection on whatever view you have bound the keyboard to, and return it from that view's onCreateInputConnection function. When you set up the EditorInfo output parameter, set the type to numeric. To listen for key presses, override the commitText function and handle it. You'll also have to deal with the possibility of composing text being set instead of commitText being initially called. It is really NOT recommended to do custom keyboard handling, its extremely complex. You're better off creating your own "keypad" with 9 numbers on it as buttons and using onClickHandlers.

Gabe Sechan
  • 77,740
  • 9
  • 79
  • 113