31
Custom Views and Touch Events

In this chapter, you will learn how to handle touch events by writing a custom subclass of View named BoxDrawingView. The BoxDrawingView class will be the star of a new project named DragAndDraw and will draw boxes in response to the user touching the screen and dragging. The finished product will look like Figure 31.1.

Figure 31.1  Boxes drawn in many shapes and sizes

Screenshot shows DragAndDraw in Android phone. The screen shows Boxes drawn in many shapes and sizes.

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;
    }
}

Run DragAndDraw to confirm that your app is set up properly. It should look like Figure 31.2.

Figure 31.2  DragAndDraw with default layout

Screenshot shows DragAndDraw in Android phone. The DragAndDraw with default layout shows the following text at the center: Hello World!
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.67.26