Example to explain the view class in Android and how to customize the View control _android

Source: Internet
Author: User
Tags cos

Simple understanding and examples of view
The basic concept of 1.View
the controls displayed in the activity are called view (the view class is the parent class of all control classes, such as text buttons)

2. Get the object representing the view in the activity
activity reads layout file generation corresponding to various view objects

TextView textview= (TextView) Findviewby (R.id.textview)

3. Set properties of view
What's the difference between @+id/and @id/, as found in XML layout files like Activity_mian.xml? Here @ can be understood as a reference, and the Extra + represents the new statement of your own

4. Set up listeners for view
A control can bind multiple listeners that are not passed by a listener to respond to a different event:

(1) Gets the object that represents the control
(2) Define a class to implement the listener interface implements Onclicklistener
(3) Generate listener objects
(4) Binding listener objects for controls

5. Examples
layout file (change to vertical layout)

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 
  xmlns:tools= "http:// Schemas.android.com/tools " 
  android:layout_width=" match_parent " 
  android:layout_height=" Match_parent " 
  android:orientation= "vertical" 
  tools:context= ". Mainactivity "> 
 
  <textview 
    android:id=" @+id/textview " 
    android:layout_width=" Match_parent " android:layout_height= "Wrap_content" 
    android:textsize= "80px" 
    android:background= "#FF0000" 
    Android:text= "Hello_world Bear"/> 
   
  <button  
    android:id= "@+id/button" 
    Match_parent " 
    android:layout_height=" wrap_content " 
    android:text=" click "/> 
 
</LinearLayout> 

Mianactivity file

Package com.xiong.fisrt_android; 
Import android.app.Activity; 
Import Android.graphics.Color; 
Import Android.os.Bundle; 
Import Android.view.Menu; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.Button; 
 
Import Android.widget.TextView; 
  public class Mainactivity extends activity {private TextView TextView; 
  Private button button; 
 
  private int count = 0; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_main); 
    TextView = (TextView) Findviewbyid (R.id.textview); 
    Button = (button) Findviewbyid (R.id.button); 
    Textview.settext ("Hello Android!!!"); 
    Textview.setbackgroundcolor (Color.Blue); Buttonelistener Buttonelistener = new Buttonelistener ();//Generate Listener Object Button.setonclicklistener (Buttonelistener);//Button binding one Listener} @Override Public boolean Oncreateoptionsmenu (Menu menu) {//inflate the menu; tHis adds items to the action bar if it is present. 
    Getmenuinflater (). Inflate (R.menu.main, menu); 
  return true; Class Buttonelistener implements onclicklistener//create a class to implement the interface that listens for events {@Override public void OnClick (Vi 
      EW arg0) {//TODO auto-generated method stub count++; 
 
    Textview.settext (Integer.tostring (count)); 
 } 
 
  } 
 
}

View customization
by inheriting view, you can easily customize a personalized control.

The main thing to implement a custom view is to rewrite the OnDraw (Canvas Canvas) function, which is invoked every time the system redraw the interface, and passes a Canvas, in which the function The contents of this view should be draw to the canvas, and almost all the content displayed by the interface is determined by this canvas. Canvas's specific painting can be easily found, it should be said that all the functions of Android is very intuitive naming, at a glance, you can see the function name may be able to understand what is the use of this function. The SDK is also the best tool for querying the Android API, and it's definitely good to use more.

The main determinant of the size of the view is that parent Layout,view can customize its own width-high minimum, but this does not guarantee that the minimum value will be reached if the parent itself is smaller than this value.

View Redraw-The system does not often call the OnDraw function of the view, in order to be able to animate the view, such as a game (but it seems that many games are implemented with more efficient Surfaceview), after the main thread is executing the logic of the program, You should call Postinvalidate () to notify the system to call the OnDraw function to redraw the interface in order to display the animation effect.

The following code is the one I wrote to simulate a two-ball collision view, mainly by a thread constantly updated view of the two ball position, after the discovery of two ball and wall collision, change the logic parameters of the ball, after the update, call Postinvalidate (), redrawing the interface. To achieve the effect

Package COM.ANDROIDCLUB.ELFMAN.HOMEWORK3; 
Import java.util.ArrayList; 
Import Java.util.Random; 
Import android.app.Activity; 
Import Android.content.Context; 
Import Android.graphics.Canvas; 
Import Android.graphics.Color; 
Import Android.graphics.Paint; 
Import Android.graphics.Paint.Style; 
Import Android.os.Bundle; 
Import Android.view.View; 
  public class Main extends activity {thescreen mscreen; 
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Mscreen is a custom view Mscreen = new Thescreen (this); 
  Setcontentview (Mscreen); }//To avoid the thread is still in progress after the program exits, resulting in unnecessary waste of system resources, when the activity exits is the time to actively stop the thread @Override public void OnDestroy () {MSCREEN.S 
    Topdrawing (); 
  Super.ondestroy (); }/** * Custom view class, collision simulation for two balls * @author windy * * */class Thescreen extends View {private static final 
  String TAG = "Draw"; 
  The control variable of the interface main thread is private Boolean drawing = false; Stores information about existing balls private ArraYlist<circle> circles; 
  Private Paint Mpaint; 
  The motion range of the two balls is public static final int WIDTH = 300; 
  public static final int HEIGHT = 400; 
  public static final Double PI = 3.14159265; 
  Paint MPaint2 = new Paint (); 
    Public Thescreen {Super (context); 
    circles = new arraylist<circle> (); 
    Two ball Circles.add (new Circle ()) added; 
    Circles.add (New Circle (20, 30, 10)); 
    Mpaint = new Paint (); 
    Mpaint.setcolor (Color.yellow); 
    Mpaint.setantialias (TRUE); 
    Mpaint2.setstyle (Style.stroke); 
    Mpaint2.setcolor (color.red); 
    Mpaint2.setantialias (TRUE); 
    Start interface thread, start Automatic Update interface drawing = true; 
  New Thread (mrunnable). Start ();  Private Runnable mrunnable = new Runnable () {//interface's main thread @Override public void run () {while 
          Drawing) {try {//update ball Position Information update (); 
          Notifies the system to update the interface, which is equivalent to calling the OnDraw function postinvalidate (); The frequency of the interface update, here is every 30Ms Update interface Thread.Sleep (30); 
        LOG.E (TAG, "drawing"); 
        catch (Interruptedexception e) {e.printstacktrace (); 
   
  } 
      } 
    } 
  }; 
  public void stopdrawing () {drawing = false; @Override public void OnDraw (Canvas Canvas) {//Border painted on Canvas canvas.drawrect (0, 0, WIDTH, HEI 
    GHT, MPaint2); On the canvas, draw the ball for (Circle circle:circles) {canvas.drawcircle (circle.x, Circle.y, Circle.radius, Mpaint 
    ); }//interface logic functions, mainly check whether the ball collision, and update the position of the ball private void update () {if (Circles.size () >1) {for 
      (int i1=0; i1<circles.size ()-1; i1++) {//When two balls collide, swap two balls for the angle value for (int i2=i1+1; i2<circles.size (); i2++) if (Checkbumb circles.ge 
          T (I1), Circles.get (I2))) {Circles.get (I1). Changederection (Circles.get (I2)); 
   }}//update the position of the ball for (Circle circle:circles)   Circle.updatelocate (); Private Boolean Checkbumb (Circle C1, Circle C2) {return (c1.x-c2.x) * (c1.x-c2.x) + (C1.Y-C2.Y) * (c1.y-c2.y      
  ) <= (C1.radius+c2.radius) * (C1.radius+c2.radius); 
    /** * Custom View's inner class, storing information for each ball * @author Windy * */class Circle {float x=50; 
    float y=70; 
    Double angle= (New Random (). Nextfloat ()) *2*pi;; 
    int speed=4; 
     
    int radius=10; 
      Public Circle () {} public Circle (float x, float y, int r) {this.x = x; 
      This.y = y; 
    Radius = R; ///Using trigonometric functions to calculate the new position value of the ball, when colliding with the boundary, change the angle of the sphere public void Updatelocate () {x = x+ (float) (Speed *math.c 
      OS (angle)); 
      LOG.V (TAG, Math.Cos (angle) + ""); 
      y = y+ (float) (Speed *math.sin (angle)); 
      LOG.V (TAG, Math.Cos (angle) + ""); if ((X+radius) >=width) {if (angle >=0 && angle <= (PI/2)) angle = Pi-angle 
        ; if (angLe > 1.5 * PI && angle <= 2*pi) angle = 3 * pi-angle; } if (X-radius <=0) {if (angle >= PI && angle <= 1.5*pi) angle = 3*p 
        I-angle; 
      if (angle >= pi/2 && angle < PI) angle = Pi-angle; 
       
    } if (Y-radius<=0 | | y+radius>=height) angle = 2*pi-angle; 
      ///Two ball exchange angle public void changederection (Circle) {Double temp = this.angle; 
      This.angle = Other.angle; 
    Other.angle = temp; 
 } 
  } 
}

This code has been written with comments, the specific next time to introduce ... It should be easy to read.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.