Reputation: 10341
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?).
Upvotes: 5
Views: 1386
Reputation: 30088
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.
Upvotes: 6