To get you started on this, we'll be using KDAB's Android utils with the humble Toast.
Toasts are small popups which are used to show the user some feedback. Check Google's API guide for more info about toasts.
The easiest way to show a toast is to use Toast.makeText(Context context, CharSequence text, int duration) static method.
This method needs 3 params:
- the context (we'll use the activity)
- the text to show
- and the duration: one of LENGTH_SHORT (0) and LENGTH_LONG (1).
Then we just need to call the show method.
Of course all the calls MUST happen on the Android UI thread.
As usual we're going to make use (abuse) of QtAndroidExtras and KDAB's Android utils (check this article to see how to add them to your project).
Let's create a simple function to show the toast:
Yep, it's that simple!
Now let's take a closer look at the code:
- We're using KDAB::Android::runOnAndroidThread to run everything on the Android UI thread.
- We're capturing message and duration params as values not as references, because as we've seen in a previous article KDAB::Android::runOnAndroidThread is (most of the time) asynchronous.
- We're using QAndroidJniObject::fromString to convert a QString to a QAndroidJniObject string object.
- We're using QAndroidJniObject::callStaticObjectMethod to call the makeText static method that returns a Toast java object. We need to pass the following parameters:
- "android/widget/Toast" is the fully qualified class name.
- "makeText" is the static method name
- "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;" - is the method signature. The method returns Landroid/widget/Toast; object and expects 3 arguments:
- Landroid/content/Context; - a Content object
- Ljava/lang/CharSequence; - a CharSequence object
- I - an int
- QtAndroid::androidActivity().object(), javaString.object(), jint(duration) are the makeText arguments.
- after we get the toast object, we call show method and we're done.
Enjoy!
5 Comments
18 - Sept - 2017
Igbaria
download full source code ?
19 - Sept - 2017
BogDan Vatra
The full source code is in the body of this article :) .
17 - Oct - 2017
Taimoor
How to do this using Qt 5.7?
17 - Oct - 2017
BogDan Vatra
Check http://doc.qt.io/qt-5/qtandroidextras-index.html to see how to add Android Extras to your project, then the source code should be the same(http://doc.qt.io/qt-5/qtandroid.html#runOnAndroidThread)).
20 - Apr - 2018
Mynor Choc
thanks, out put it in my android app. :)