Sign up for the KDAB Newsletter
Stay on top of the latest news, publications, events and more.
Go to Sign-up
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:
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:
enum Duration {
SHORT = 0,
LONG = 1
};
void showToast(const QString &message, Duration duration = LONG) {
// all the magic must happen on Android UI thread
QtAndroid::runOnAndroidThread([message, duration] {
QAndroidJniObject javaString = QAndroidJniObject::fromString(message);
QAndroidJniObject toast = QAndroidJniObject::callStaticObjectMethod("android/widget/Toast", "makeText",
"(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;",
QtAndroid::androidActivity().object(),
javaString.object(),
jint(duration));
toast.callMethod<void>("show");
});
}
Yep, it's that simple!
Now let's take a closer look at the code:
Enjoy!
showToast(QLatin1String("Hello from Qt"));
Wrapping tiny JS libraries in QML to do quick and simple things effortlessly and elegantly.
Factors to Consider When Choosing a Software Stack
A New Qt (5.x & 6.x) Library for Complete Shared Storage Access
Stay on top of the latest news, publications, events and more.
Go to Sign-up
Upgrade your applications from Qt 5 to Qt 6 with KDAB’s migration services. Get a free migration assessment and join a hands-on workshop to prepare your team for a successful transition!
Learn more
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. :)