Ví dụ 3: Mở một Activity khác đồng thời truyền dữ liệu qua và xử lý kết quả trả về.
- Ví dụ này bạn sẽ biết cách xử lý kết quả trả về như thế nào.
- Bạn xem hình minh họa:
- Chúng ta sẽ dựa vào requestCodeID và resultCode để xử lý.
- Việc tạo Intent trong trường hợp này cũng y xì như trường hợp trước. Nó chỉ khác hàm gọi :
- Chương trình đơn giản là MainActivity sẽ có 1 Button và ListView như hình bên dưới:
- Khi nhập số và nhấn “lưu số gốc” thì nó sẽ truyền số này qua MainActivity và cập nhật ListView với đúng số gốc này.
- Bạn chú ý là phải đóng Dialog ngay, vì nếu không đóng thì onActivityResult sẽ không sảy ra. onActivityResult chỉ sảy ra trong foreground life time.
- Ta tiến hành khám phá ứng dụng:
- Xem cấu trúc chương trình:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" ><Button android:id="@+id/btnopenactivity" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Mở Activity Nhập Dữ Liệu" /><ListView android:id="@+id/lvdata" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView></LinearLayout> |
- Source XML của activity_input_data.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".InputDataActivity" ><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" ><TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Nhập số:" /><EditText android:id="@+id/editNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" ><requestFocus /> </EditText></LinearLayout><LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" ><Button android:id="@+id/btnSave1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Lưu Bình Phương" /><Button android:id="@+id/btnSave2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Lưu Số gốc" /></LinearLayout></LinearLayout> |
0 nhận xét:
Đăng nhận xét