I am trying to figure a good way to start an activity from a click on the floating action button. My FAB is located in mainactivity.xml. My MainActivity consists of bottom navigation with fragments. I need to implement a different on click action determined by a fragment that is shown.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_add);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fabClicked();
}
});
fabClicked
Method
public void fabClicked() {
Object id = getSupportFragmentManager().findFragmentById(R.id.container);
if ((getSupportFragmentManager().findFragmentById(R.id.fragment_1)).equals(id)) {
Intent intent1 = new Intent(MainActivity.this, Add1.class);
startActivity(intent1);
}
else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_2)).equals(id)) {
Intent intent2 = new Intent(MainActivity.this, Add2.class);
startActivity(intent2);
}
else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_3)).equals(id)) {
Intent intent3 = new Intent(MainActivity.this, Add3.class);
startActivity(intent3);
}
else if ((getSupportFragmentManager().findFragmentById(R.id.fragment_home)).equals(id)) {
//plan to add to code to hide fab on homescreen
}
}
Your approach is good, but it's doing many unnecessary expensive Fragment lookups.
You can get the navigation id of the current Fragment with:
navController.getCurrentDestination().getId()
You can then use this returned id to do different things in the click listener based on the Fragment, like so:
fun fabClicked() {
val id = navController.getCurrentDestination().getId()
val class = when(id) {
R.id.fragment_1 -> Add1::class
R.id.fragment_2 -> Add2::class
// etc
}
startActivity(Intent(this, class.javaClass))
}
In this way, you don't need to do Fragment look-ups for each condition, just simply compare ids. You can also extract the shared startActivity
logic (as shown here) to make this much more concise.