Chapter 31 Custom Views and Touch Events
Setting Up the DragAndDraw Project
Create a new project named DragAndDraw. Select API 19 as the minimum SDK and create an empty
activity. Name the activity DragAndDrawActivity.
DragAndDrawActivity will be a subclass of SingleFragmentActivity that inflates the usual single-
fragment-containing layout. Copy SingleFragmentActivity.java and its activity_fragment.xml
layout file into the DragAndDraw project.
In DragAndDrawActivity.java, make DragAndDrawActivity a SingleFragmentActivity that creates
a DragAndDrawFragment (a class that you will create next).
Listing 31.1 Modifying the activity (DragAndDrawActivity.java)
public class DragAndDrawActivity extends AppCompatActivity SingleFragmentActivity {
@Override
protected Fragment createFragment() {
return DragAndDrawFragment.newInstance();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
}
To prepare a layout for DragAndDrawFragment, rename the activity_drag_and_draw.xml layout file
to fragment_drag_and_draw.xml.
DragAndDrawFragment’s layout will eventually consist of a BoxDrawingView, the custom view
that you are going to write. All of the drawing and touch-event handling will be implemented in
BoxDrawingView.
Create a new class named DragAndDrawFragment and make its superclass
android.support.v4.app.Fragment. Override onCreateView(...) to inflate
fragment_drag_and_draw.xml.
Listing 31.2 Creating the fragment (DragAndDrawFragment.java)
public class DragAndDrawFragment extends Fragment {
public static DragAndDrawFragment newInstance() {
return new DragAndDrawFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_drag_and_draw, container, false);
return v;
}
}