In the installation of the back button on the fragment I used to define it in the parent Activity and call it. It is better to call the contents directly from each Fragment without putting it in Activity As a veteran engineer pointed out, I will leave both patterns as a memorandum.
MainActivity.java
public class MainActivity extends AppCompatActivity {
//Define back button
public void setupBackButton(boolean enableBackButton) {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(enableBackButton);
}
}
Fragment1.java
//Call in onCreateView
MainActivity activity = (MainActivity) getActivity();
activity.setupBackButton(true);
setHasOptionsMenu(true); //Settings required to use ActionBar with Fragment
Fragment2.java
//Call in onCreateView
MainActivity activity = (MainActivity) getActivity();
activity.setupBackButton(false);
Fragment1.java
//Call in onCreateView
.setupBackButton()
setHasOptionsMenu(true); //Settings required to use ActionBar with Fragment
//Defined in Fragment class
public void setupBackButton() {
AppCompatActivity activity = (AppCompatActivity) getActivity();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
Fragment2.java
//Call in onCreateView
.hideBackButton()
//Defined in Fragment class
public void hideBackButton() {
AppCompatActivity activity = (AppCompatActivity) getActivity();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
}
It looks the same at first glance, but the source of Activity is different! ①MainActivity activity = (MainActivity) getActivity(); ②AppCompatActivity activity = (AppCompatActivity) getActivity();
It is said that it is better to stop writing on the premise of a specific activity (Main Activity in this case). This is because the more prerequisite classes (classes you define), the harder it is for your code to make safe changes.
If the acquisition destination is AppCompatActivity, it is an inheritance source, so it is almost never changed and it is highly safe. I want to be a strong engineer who can implement with a view to the future.
Recommended Posts