Fragment's onOptionsItemSelected doesn't get called

后端 未结 5 1991
离开以前
离开以前 2021-02-01 03:17

My fragment replaces the parent Activity options with a specific option item but when I click on the item, only activity\'s onOptionItemSelected gets called eventho

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 03:45

    I found solution i.e

    Fragment.class

     @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // Do something that differs the Activity's menu here
        //MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.wifinity_setting, menu);
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            SpannableString spanString = new SpannableString(menu.getItem(i).getTitle().toString());
            spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, spanString.length(), 0); //fix the color to white
            item.setTitle(spanString);
        }
        super.onCreateOptionsMenu(menu, inflater);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
    
            case R.id.menu1:
                Intent intent3 = new Intent(context, activity.class);
                startActivity(intent3);
                return true;
    
        }
        return true;
    }
    

    ACtivity.class

    overide the onOptionsItemSelected() // fragmnets onOptionselected method get called .. this solution works for me

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
    
            default:
                if(fragment != null)
                    fragment.onOptionsItemSelected(item);
        }
        return true;
    }
    

提交回复
热议问题