【问题标题】:onOptionsItemSelected not being called when Back button is pressed on actionBar在 actionBar 上按下后退按钮时未调用 onOptionsItemSelected
【发布时间】:2016-02-24 16:01:01
【问题描述】:

就这么简单,当我按下返回按钮时,什么也没有发生。 这是我正在运行的代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tm_activity_inicio_resumen, container, false);

    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_left2);

    return view;
}

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
            break;
    }
    return true;
}

这个实现有问题吗?

【问题讨论】:

  • 会在activity中调用,而不是在fragment中调用。

标签: android android-fragments android-actionbar


【解决方案1】:

更改此代码。

@Override
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) {
    case android.R.id.home: 
        onBackPressed();
        return true;
    }

return super.onOptionsItemSelected(item);
}

【讨论】:

    【解决方案2】:

    如果你想要片段上的操作栏菜单,那么

    覆盖片段上的 onCreateOptionsMenu。并清除活动菜单

        @Override
                public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
                    super.onCreateOptionsMenu(menu, inflater);
            menu.clear();
    
    //if you dont have options skip inflate 
                        inflater.inflate(R.menu.menu_second, menu);
                }
    

     @Override
        public boolean onOptionsItemSelected(MenuItem item) {
    
              int id = item.getItemId();
                if (id == android.R.id.home) {
                Toast.makeText(getActivity().getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
            return true;
        }
    
    
    return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多