Simple Android App with Kivy
This guide demonstrates how to create a simple Android application using Kivy. Kivy is an open-source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. To package the app for Android, we use Buildozer.
Modules Used:
kivy: The framework for building the app UI and logic.
Prerequisites
- Python: Installed on your development machine.
- Linux Environment: Buildozer (the packaging tool) works best on Linux. If you are on Windows, use WSL2 (Windows Subsystem for Linux) or a Virtual Machine.
Installation
Install Kivy on your development machine to test the app:
pip install kivy
The Code
Save this as main.py. Kivy applications usually require the main file to be named main.py for packaging.
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
class MyAndroidApp(App):
def build(self):
# 1. Main Layout
# BoxLayout arranges widgets in a vertical or horizontal box
layout = BoxLayout(orientation='vertical', padding=20, spacing=10)
# 2. Label Widget
self.label = Label(
text="Hello, Android!",
font_size='30sp',
color=(1, 1, 1, 1) # White
)
layout.add_widget(self.label)
# 3. Button Widget
btn = Button(
text="Click Me",
size_hint=(1, 0.2), # Width: 100%, Height: 20% of parent
background_color=(0, 0.5, 1, 1) # Blueish
)
# Bind the button press to a function
btn.bind(on_press=self.on_button_click)
layout.add_widget(btn)
return layout
def on_button_click(self, instance):
self.label.text = "You clicked the button!"
self.label.color = (0, 1, 0, 1) # Change text to Green
if __name__ == '__main__':
MyAndroidApp().run()
Testing Locally
You can run this script on your computer to test the UI logic before packaging.
python main.py
Packaging for Android (Buildozer)
To turn this main.py into an .apk file that runs on Android, follow these steps in your Linux/WSL environment.
-
Install Buildozer Dependencies:
sudo apt update sudo apt install -y git zip unzip openjdk-17-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev pip3 install --user --upgrade buildozer -
Initialize Buildozer: Navigate to the directory containing your
main.pyand run:buildozer initThis creates a
buildozer.specfile. You can edit this file to change the app name, package domain, permissions, etc. -
Build the APK: Connect your Android phone via USB (ensure USB Debugging is enabled) and run:
# Build, deploy, and run the app on the connected device buildozer android debug deploy runNote: The first build will take a long time as it downloads the Android SDK/NDK.
If you just want the APK file without deploying:
buildozer android debugThe
.apkfile will be in thebin/directory.
Usage
Once installed on your phone, tap the app icon to launch it. It will display the label and button defined in your Python script.