2013-07-02 53 views
24

Tôi muốn thêm một nút vào Thanh tác vụ sang phía bên tay phải của Ví dụ như trong ảnh chụp màn hình này:Cách thêm nút trong ActionBar (Android)?

a screenshot of an actionbar with no buttons. the title is 'Example'

tôi nhận được actionBar trong phương pháp onCreate như:

ActionBar actionBar = getActionBar(); 
actionBar.setDisplayHomeAsUpEnabled(true); 

và nút quay lại (phương thức onOptionsItemSelected) như sau:

public boolean onOptionsItemSelected(MenuItem item){ 
    Intent myIntent = new Intent(getApplicationContext(),MainActivity.class); 
    startActivityForResult(myIntent, 0); 
    return true; 
} 

Làm cách nào để thêm nút?

Trả lời

72

bạn phải tạo một mục nhập bên res/menu, override onCreateOptionsMenu và thổi phồng nó

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.yourentry, menu); 
    return true; 
} 

một mục nhập cho menu có thể là:

<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item 
     android:id="@+id/action_cart" 
     android:icon="@drawable/cart" 
     android:orderInCategory="100" 
     android:showAsAction="always"/> 
</menu> 
+0

Ok.That works.But tôi không hiểu sử dụng orderInCategory và giá trị của nó như là 100. – Ponting

+0

Đó là một số nguyên đại diện cho thứ tự của "tầm quan trọng" của mục, trong một nhóm. Bạn có thể thay đổi nó. Miễn là bạn có một hoặc hai phần tử trong trình đơn, nó không tạo sự khác biệt. bạn có thể đọc về nó [ở đây] (http://developer.android.com/guide/topics/resources/menu-resource.html) – Blackbelt

+0

Cảm ơn bạn.Câu hỏi khác là tôi thêm menu này vào hoạt động khác nhưng hiển thị khác nút thay vì điều này. Làm thế nào tôi có thể làm điều đó? – Ponting

14

Một hoạt động populates ActionBar trong phương pháp onCreateOptionsMenu() của nó.

Thay vì sử dụng setcustomview(), chỉ cần ghi đè onCreateOptionsMenu như thế này:

@Override  
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.mainmenu, menu); 
    return true; 
} 

Nếu một hành động trong ActionBar được chọn, phương pháp onOptionsItemSelected() được gọi. Nó nhận hành động được chọn làm tham số. Dựa trên thông tin này bạn mã có thể quyết định việc cần làm ví dụ:

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
    case R.id.menuitem1: 
     Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show(); 
     break; 
    case R.id.menuitem2: 
     Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show(); 
     break; 
    } 
    return true; 
} 
0

Nhờ @Blackbelt! Phương pháp chữ ký mới cho lạm phát thực đơn là thế này:

@Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
     inflater.inflate(R.menu.my_meny, menu); 
} 
Các vấn đề liên quan