| 1 | ''' |
| 2 | Example of an Android filechooser. |
| 3 | ''' |
| 4 | |
| 5 | from textwrap import dedent |
| 6 | |
| 7 | from plyer import filechooser |
| 8 | |
| 9 | from kivy.app import App |
| 10 | from kivy.lang import Builder |
| 11 | from kivy.properties import ListProperty |
| 12 | from kivy.uix.button import Button |
| 13 | |
| 14 | |
| 15 | class FileChoose(Button): |
| 16 | ''' |
| 17 | Button that triggers 'filechooser.open_file()' and processes |
| 18 | the data response from filechooser Activity. |
| 19 | ''' |
| 20 | |
| 21 | selection = ListProperty([]) |
| 22 | |
| 23 | def choose(self): |
| 24 | ''' |
| 25 | Call plyer filechooser API to run a filechooser Activity. |
| 26 | ''' |
| 27 | filechooser.open_file(on_selection=self.handle_selection) |
| 28 | |
| 29 | def handle_selection(self, selection): |
| 30 | ''' |
| 31 | Callback function for handling the selection response from Activity. |
| 32 | ''' |
| 33 | self.selection = selection |
| 34 | |
| 35 | def on_selection(self, *a, **k): |
| 36 | ''' |
| 37 | Update TextInput.text after FileChoose.selection is changed |
| 38 | via FileChoose.handle_selection. |
| 39 | ''' |
| 40 | App.get_running_app().root.ids.result.text = str(self.selection) |
| 41 | |
| 42 | |
| 43 | class ChooserApp(App): |
| 44 | ''' |
| 45 | Application class with root built in KV. |
| 46 | ''' |
| 47 | |
| 48 | def build(self): |
| 49 | return Builder.load_string(dedent(''' |
| 50 | <FileChoose>: |
| 51 | |
| 52 | BoxLayout: |
| 53 | |
| 54 | BoxLayout: |
| 55 | orientation: 'vertical' |
| 56 | |
| 57 | TextInput: |
| 58 | id: result |
| 59 | text: '' |
| 60 | hint_text: 'selected path' |
| 61 | |
| 62 | FileChoose: |
| 63 | size_hint_y: 0.1 |
| 64 | on_release: self.choose() |
| 65 | text: 'Select a file' |
| 66 | ''')) |
| 67 | |
| 68 | |
| 69 | if __name__ == '__main__': |
| 70 | ChooserApp().run() |