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).
Package Com.example.lhb.contentprovider1;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.canvas;import Android.graphics.paint;import Android.view.view;public class MyView extends view{public MyView (context context) { super (context); } @Override protected void OnDraw (canvas canvas) { super.ondraw (canvas); Paint paint=new paint (); 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.
Package Com.example.lhb.contentprovider1;import Android.app.activity;import Android.os.bundle;import Android.view.motionevent;import Android.view.view;import Android.widget.framelayout;public class MainActivity Extends Activity { @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Framelayout framelayout= (framelayout) Findviewbyid (r.id.layout); Final MyView myview=new MyView (mainactivity.this); Myview.setontouchlistener (New View.ontouchlistener () { @Override public boolean OnTouch (View V, motionevent Event) { myview.invalidate (); return true; } }); Framelayout.addview (MyView); }}
Custom View components for Android Studio Development Basics