2016-10-03 53 views
1

如何爲我的android應用程序創建代碼當我按下工具欄上的後退按鈕(Action Bar)時,會發生一些代碼。按下工具欄上的後退按鈕

我試過了,但不起作用。

添加到主要活動。 onbackpress方法

@Override 
public void onBackPressed() { 
    super.onBackPressed(); 
    stopActivityTask(); 
} 
+1

檢查我的回答:http://stackoverflow.com/questions/39827732/when-toolbar-back-button-is-pressed/39827808#39827808 –

+0

的onBackPressed()方法將在用戶按下_Back_按鈕時被調用;如果我是對的,你的意思是叫_Home_按鈕。 –

回答

2

你可以試試這個方式..

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
switch (item.getItemId()) { 
    case android.R.id.home: 
     // this takes the user 'back', as if they pressed the left-facing  

     triangle icon on the main android toolbar. 
     // if this doesn't work as desired, another possibility is to call 

     stopActivityTask(); // finish() here. 
     getActivity().onBackPressed(); 
     return true; 
    default: 
     return super.onOptionsItemSelected(item); 
} 
} 

如果不起作用

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     // Title and subtitle 
     toolbar.setTitle(R.string.about_toolbar_title); 
     toolbar.setNavigationIcon(R.drawable.ic_action_back); 
     toolbar.setNavigationOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       stopActivityTask(); 
       finish(); 
      } 
     }); 
+0

謝謝..第一種方法工作.. –

1
@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 

    int id = item.getItemId(); 

    // click on icon to go back 
    //triangle icon on the main android toolbar. 

    if (id == android.R.id.home) { 
     //your code 
     return true; 
    } 
    return super.onOptionsItemSelected(item); 
} 
0
private Toolbar toolbar; 

然後在你onCreate方法添加此

toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

然後添加這些行:

 @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
     /* 
      ADD WHAT YOU WANT TO DO WHEN ARROW IS PRESSED 
     */ 
     return super.onOptionsItemSelected(item); 
} 
相關問題