In the new Android Studio, every time I create an activity from the wizard it will create the following structure:
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
}
}
Notice there's the activity and it contains a fragment place holder. Is this considered a good practice? is it because if you wanted in the future to support tablets or replace fragment then you could (and thats why its the new default in Android studio?).
Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.
We can't create multi-screen UI without using fragment in an activity, After using multiple fragments in a single activity, we can create a multi-screen UI. Fragment cannot be used without an Activity. While Using fragments in the project, the project structure will be good and we can handle it easily.
Understanding Fragments Using the support library, fragments are supported back to all relevant Android versions. Fragments encapsulate views and logic so that it is easier to reuse within activities. Fragments are standalone components that can contain views, events and logic.
Generally speaking, yes, you should try to use fragments as much as possible, so that you can have different layouts for different size / aspect ratio devices.
And yes, that's why Android Studio generates code that way by default.
However, like any good rule, there are exceptions. Sometimes, an activity is simple, and will not differ on different devices. In that case, a fragment doesn't necessarily make sense.
In short, use fragments by default. Go with just an activity in the few cases where it makes sense you in your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With