Bài 23: Context Menu trong Android

Leave a Comment
- Ở đây Tôi làm một ví dụ đơn giản về Context Menu. Giao diện có 1 Button, khi nhấn thật lâu vào nó thì sẽ hiển thị Context Menu cho phép đổi màu chữ : Màu đỏ, màu xanh lá cây và xanh dương:
23_ctx_0
- Ở hình trên là khi Context Menu hiển thị ra, Tôi chọn Red –> Màu của Button sẽ chuyển thành màu đỏ.
- Bạn xem cấu trúc thư mục của Project này và nội dung bên trong của Context menu:
23_ctx_1- Tiếp tục bạn Double click vào strings.xml , Tôi có định nghĩa một số color trong này:
23_ctx_2- Ở trong strings.xml , Tôi tạo 3 tag color : Red, Green, Blue; Nội dung bạn phải để dạng Hex Color. 3 màu này sẽ được triệu gọi trong hàm xử lý sự kiện khi người sử dụng chọn từng Menu Item trong Context Menu.
- Bạn xem nội dung MainActivity.java:
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
package tranduythanh.com;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.Button;
 
public class MainActivity extends Activity {
 
Button btnCtx;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 btnCtx=(Button) findViewById(R.id.btnshowcontext);
 registerForContextMenu(btnCtx);
 }
 @Override
 public void onCreateContextMenu(ContextMenu menu, View v,
 ContextMenuInfo menuInfo) {
 // TODO Auto-generated method stub
 super.onCreateContextMenu(menu, v, menuInfo);
 getMenuInflater()
 .inflate(R.menu.my_context_menu, menu);
 }
 @Override
 public boolean onContextItemSelected(MenuItem item) {
 switch(item.getItemId())
 {
 case R.id.itemRed:
 btnCtx.setTextColor(
 getResources().getColor(R.color.clrred));
 break;
 case R.id.itemGreen:
 btnCtx.setTextColor(
 getResources().getColor(R.color.clrgreen));
 break;
 case R.id.itemBlue:
 btnCtx.setTextColor(
 getResources().getColor(R.color.clrblue));
 break;
 }
 return super.onContextItemSelected(item);
 }
}
- Bạn quan sát dòng lệnh:
+ Dòng lệnh 22 , onCreateContextMenu dùng để nạp Context Menu XML vào ứng dụng
+ Dòng lệnh 30, onContextItemSelected dùng để xử lý sự kiện.
+ Để đăng ký Context Menu cho đối tượng nào thì bạn làm giống như dòng 19:  registerForContextMenu(btnCtx);
getResources().getColor(R.color.clrred) dùng để lấy màu từ XML Resource
+ Như vậy bạn đã biết cách sử dụng Context Menu
+ Bạn có thể tải coding mẫu ở đây: http://www.mediafire.com/?8s368sl4z594y85
Chúc các bạn thành công.

0 nhận xét:

Đăng nhận xét