Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 17  Two-Pane Master-Detail Interfaces


Modifying SingleFragmentActivity


CrimeListActivity is a subclass of SingleFragmentActivity. Currently, SingleFragmentActivity
is set up to always inflate activity_fragment.xml. To make SingleFragmentActivity more flexible,
you are going to enable a subclass to provide its own resource ID for the layout instead.


In SingleFragmentActivity.java, add a protected method that returns the ID of the layout that the
activity will inflate.


Listing 17.1  Making SingleFragmentActivity flexible
(SingleFragmentActivity.java)


public abstract class SingleFragmentActivity extends AppCompatActivity {


protected abstract Fragment createFragment();


@LayoutRes
protected int getLayoutResId() {
return R.layout.activity_fragment;
}


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
setContentView(getLayoutResId());


FragmentManager fm = getSupportFragmentManager();
...
}
}


The default implementation of SingleFragmentActivity will work the same as before, but
now its subclasses can choose to override getLayoutResId() to return a layout other than
activity_fragment.xml. You annotate getLayoutResId() with @LayoutRes to tell Android Studio
that any implementation of this method should return a valid layout resource ID.

Free download pdf