Skip to content

Commit 1235b09

Browse files
committed
Add Android ButtonClickListener
1 parent 0c4b261 commit 1235b09

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

apps/android_pythonnative_3/app/src/main/java/com/pythonnative/pythonnative/MainActivity.kt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,14 @@ class MainActivity : AppCompatActivity() {
3636
// val pyButton = createButtonModule.callAttr("create_button", this).toJava(Button::class.java)
3737
// layoutMain.addView(pyButton)
3838

39-
// val createWidgetsModule = py.getModule("create_widgets")
40-
// val pyLayout = createWidgetsModule.callAttr("create_widgets", this).toJava(LinearLayout::class.java)
41-
// layoutMain.addView(pyLayout)
42-
43-
val createLayoutModule = py.getModule("create_pn_layout")
44-
val pyLayout = createLayoutModule.callAttr("create_pn_layout", this).toJava(LinearLayout::class.java)
39+
val createWidgetsModule = py.getModule("create_widgets")
40+
val pyLayout = createWidgetsModule.callAttr("create_widgets", this).toJava(LinearLayout::class.java)
4541
layoutMain.addView(pyLayout)
4642

43+
// val createLayoutModule = py.getModule("create_pn_layout")
44+
// val pyLayout = createLayoutModule.callAttr("create_pn_layout", this).toJava(LinearLayout::class.java)
45+
// layoutMain.addView(pyLayout)
46+
4747
// val createConstraintLayoutModule = py.getModule("create_constraint_layout")
4848
// val pyLayout = createConstraintLayoutModule.callAttr("create_constraint_layout", this).toJava(ConstraintLayout::class.java)
4949
// layoutMain.addView(pyLayout)

apps/android_pythonnative_3/app/src/main/python/create_widgets.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,26 @@
1-
from java import jclass
1+
from java import dynamic_proxy, jclass, static_proxy
2+
import random
3+
4+
# Import View class which contains OnClickListener
5+
View = jclass('android.view.View')
6+
Color = jclass('android.graphics.Color')
7+
8+
9+
class ButtonClickListener(dynamic_proxy(View.OnClickListener)):
10+
def __init__(self, button):
11+
super().__init__()
12+
self.button = button
13+
14+
def onClick(self, view):
15+
# Generate a random hex color.
16+
color = "#" + "".join(
17+
[random.choice("0123456789ABCDEF") for _ in range(6)])
18+
19+
# Set the button's background color.
20+
self.button.setBackgroundColor(Color.parseColor(color))
21+
22+
# Print something to the console.
23+
print("Button clicked! New color is " + color)
224

325

426
def create_widgets(context):
@@ -62,6 +84,7 @@ def create_widgets(context):
6284
# Create Button
6385
button = Button(context)
6486
button.setText("Button created in Python")
87+
button.setOnClickListener(ButtonClickListener(button))
6588
layout.addView(button)
6689

6790
# Create TextView

0 commit comments

Comments
 (0)