In general, you do not use the view and ViewGroup classes directly, but use their subclasses instead. For example, to display a picture that can be imageview with a subclass of the view class, developing a custom view component can be divided into two main steps:
First, create a view class that inherits from the Android.view.View class, and override the constructor method.
as follows, create a new Java class file named Myview.java, overriding a constructed method with context and the OnDraw () method (used to redraw the background of the Activity window).
PackageCom.example.lhb.contentprovider1;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Paint;ImportAndroid.view.View; Public classMyViewextendsview{ PublicMyView (Context context) {Super(context); } @Overrideprotected voidOnDraw (canvas canvas) {Super. OnDraw (canvas); Paint Paint=NewPaint (); Bitmap Bitmap= Bitmapfactory.decoderesource ( This. Getresources (), r.drawable.bg); Canvas.drawbitmap (Bitmap,0,0, paint); if(bitmap.isrecycled ()) {bitmap.recycle (); } }}
Second, in the project activity, create and instantiate the custom MyView class and add it to the layout manager.
As below, in the main active OnCreate () method, first get the frame layout manager, create the MyView object, and then add the touch listener event.
PackageCom.example.lhb.contentprovider1;Importandroid.app.Activity;ImportAndroid.os.Bundle;Importandroid.view.MotionEvent;ImportAndroid.view.View;Importandroid.widget.FrameLayout; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Framelayout Framelayout=(framelayout) Findviewbyid (r.id.layout); FinalMyView myview=NewMyView (mainactivity. This); Myview.setontouchlistener (NewView.ontouchlistener () {@Override Public BooleanOnTouch (View V, motionevent event) {myview.invalidate (); return true; } }); Framelayout.addview (MyView); }}
Custom View components for Android Studio Development Basics