-1

I want to add Filter option in Tool Bar which can be used in multiple fragments by each fragment has a different filter. For example, if I click A fragment a toolbar appears with filter option having today date, and if I click B fragment a toolbar appears with filter option having this start month date. I am getting Icon in each and every Fragment but How to use click event in the fragment

  private void setupToolBar() {
    drawerLayout = findViewById(R.id.drawer_layout);
    initNavigationDrawer();
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_menu, menu);
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_filter:
            Toast.makeText(this,"Main activity",Toast.LENGTH_LONG).show();
            break;
        default:
            break;
    }
    return true;
}
Tanveer Munir
  • 1,956
  • 1
  • 12
  • 27
Rex
  • 57
  • 8
  • This answer might help https://stackoverflow.com/a/24979551/7200713, let me know if you want it to be explained in detail.. – Kaveri Feb 22 '19 at 07:39

1 Answers1

0

Try Like this

//Here i am doing by using string you can check current Fragment so it will change according to Fragment

public class YourActivity extends Activity {
  private Menu menu;
  private String DateTitle = "Date'";
  private String MonthTitle = "Month";
  private boolean inBed = false;
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    // Create your menu...
    this.menu = menu;
    return true;
  }
  private void updateMenuTitles() {
    MenuItem bedMenuItem = menu.findItem(R.id.action_filter);

    >//Here i am doing by using string you can check current Fragment so it will change according to Fragment 

if (inBed) {
  bedMenuItem.setTitle(MonthTitle);
} else {
  bedMenuItem.setTitle(DateTitle);
}
  }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case R.id.action_filter:
        if(item.getTitle().toString() == "Date"){
        Toast.makeText(this,"Date",Toast.LENGTH_LONG).show();
        }            
        if(item.getTitle().toString() == "Month")
        Toast.makeText(this,"Month",Toast.LENGTH_LONG).show();
        break;
    default:
        break;
}
return true;
}

}
VikaS GuttE
  • 1,636
  • 2
  • 14
  • 38