[英]understanding onOptionsItemSelected
我有2個帶有操作欄的活動,其onCrate
方法中包含以下代碼:
getActionBar().setDisplayHomeAsUpEnabled(true);
這是onOptionsItemSelected
:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.icon:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
第一個活動具有父活動(在清單中配置),第二個活動剛剛從片段打開(沒有在清單中配置父片段)。 在第一個活動中,當我單擊圖標時,活動item.getItemId()
值與android.R.id.icon
相同,后者落入switch語句(例如: Android.R.id.icon
)。 在第二個活動中,這些值是不同的。 為什么會這樣? 我想在這兩種活動中都是Android.R.id.icon
。
使用這種類型的代碼
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1, 1, 1, "Done").setIcon(R.drawable.img_done)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menu.add(1, 2, 2, "Save").setIcon(R.drawable.img_save)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
// Write your code for the first button
break;
case 2:
// Write your code for the second button
break;
}
return true;
}
而不是使用android.R.id.icon
使用android.R.id.home
試試這段代碼:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
有關詳細信息,請查看此鏈接
嘗試這個:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.icon: //where 'icon' would be your item ID from menu.xml.
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
你使用的android.R.id.icon
可能是錯的。 而不是你可能想要使用R.id.icon
。
R.id.icon
和android.R.icon
文件之間存在差異。
還要確保您沒有使用以下導入
import android.R;
它可能會導致不必要的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.