2.1 Android View Components

Source: Internet
Author: User

1 View components and container components

1) Most of the Android UI components are stored with Android.widget packets and their sub-packages, Android.view and their sub-packages

2) Android all UI components inherit from the view class

3) The view class has a very important subclass: ViewGroup, but ViewGroup is often used as a container for other components, and Android uses the combo mode to design the view and ViewGroup

ViewGroup can be used as a view, but is generally used as a container, but ViewGroup is an abstract class.

is actually used by his subclasses, such as various layout managers

/**
* <p>
* A <code>ViewGroup</code> is a special view this can contain other views
* (called children.) The view group is the base class for layouts and views
* Containers. This class also defines the
* {@link Android.view.ViewGroup.LayoutParams} class which serves as the base
* Class for layouts parameters.
x/
Public abstract class ViewGroup extends View implements Viewparent, Viewmanager {}

2 using an XML file to control the UI

<relativelayout 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:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=" com.examples.viewgroup.MainActivity ">    <textview        Android:id= "@+id/text"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_content"        />    <button         android:id= "@+id/button"        android:layout_width= "Wrap_content        " android:layout_height= "Wrap_content"        /></relativelayout>

The code in SRC is

1Super. OnCreate (Savedinstancestate);2Super. Setcontentview (R.layout.activity_main);3 Button B =(Button) Findviewbyid (R.id.button);4Final TextView Text =(TextView) Findviewbyid (R.id.text); 5 B.setonclicklistener (new Onclicklistener () { 6 7 @Override 8 public void OnC Lick (View v) { 9 // TODO auto-generated Method stubText.settext ("Current system time" +new Date ()); C17>11 });                

3 Full control of the UI with code

1Super.oncreate (savedinstancestate);2//Create a linear layout3 LinearLayout layout=New LinearLayout (This);4//Set the activity display layout5Setcontentview (layout);6//Vertical list7Layout.setorientation (linearlayout.vertical);8//Create a TextView9 Final TextView Text =New TextView (This);Ten Button B =New Button (This);11//To add a string resource to a string XML file under the value folderB.settext (R.String. button);13//The actual content size fills the button controlB.setlayoutparams (NewViewgroup.layoutparams (viewgroup.layoutparams.wrap_content,viewgroup.layoutparams.wrap_content));15Layout.addview (b);16Layout.addview (text);17//To add a listener event to a buttonB.setonclicklistener (new Onclicklistener () { @Override public   void OnClick (View v) { // TODO auto-generated Method Stubtext.settext (" Current time " +new java.util.Date ());  } );                 

Run results

  

This simple function can be achieved in both ways, but using the code to control the UI is rather bloated, and using the XML file Configuration interface shows the layered thinking of MVC. The interface and logic-good coupling can be used to facilitate the maintenance and modification of the latter.

4. Using the XML file and code blending control UI Interface

1) Place the picture file under the drawable-ldpi folder

2) define a linear layout file Fistlayout.xml

  

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "Vertical" >    

Android:id= "@+id/image"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:contentdescription= "@+id/test"
/></linearlayout>

3) Control the image transformation in the code

  

       Super.oncreate (savedinstancestate);
Setcontentview (r.layout.firstlayout);
Final ImageView image = (ImageView) Findviewbyid (r.id.image);
Image.setimageresource (Images[0]);
Image.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
Image.setimageresource (Images[++i%images.length]);
}
});

5. Developing the Custom View

To implement a custom view, you must define a subclass that inherits the view base class, and then override one or more methods of the view class, typically overridden by the following methods

Constructor: The overriding constructor is the most basic way to customize the view, and the constructor is called when Java code creates a view instance or loads and constructs an interface from an XML file.

Onfinishinflate (): callback method that is invoked when the application loads the component from an XML layout file and uses it to build the interface

Onmeasure (int,int): Call this method to detect the size of the view component and all the subcomponents it contains

OnLayout (Boolean,int,int,int,int): The method is called back when the component needs to know/size the allocator subassembly

Onsizechanged (Int,int,int,int): Callback This method when the size of the component is changed

OnDraw (Canvas): The component will draw his content when the callback method is drawn

OnKeyDown (int,keyevent): Triggers the method when a case is pressed

OnKeyUp (int,keyevent): Triggers This method when a key is released

Ontrackballevent (motionevent): Triggers This method when a Trackball event occurs

Ontouchevent (motionevent): triggered when touched

Onwindowfocuschanged (Boolean): triggered when the component gets/loses focus

Onattachedtowindow (): Triggers this method when a component is placed into a window

Ondetachedfromwindow (): Triggers this method when a component is detached from a window

onwindowvisibilitychanged (int): Triggers when the visibility of the window containing the build changes

In general, we will not rewrite all the methods, but rather rewrite some of the methods as needed

Below, create a small ball that follows the finger motion.

1) Create a Drawviw class that inherits from view and overrides some methods

  

public class Drawview extends View {public Drawview (context context) {super (context);//TODO Auto-generated Constructor St ub}public float Currx = 50;public float CurrY = 50; Paint p = new paint ();//override OnDraw method public void OnDraw (canvas canvas) {super.ondraw (canvas);p. SetColor (color.red); Canvas.drawcircle (Currx, CurrY, p);} Override Touch Event @overridepublic Boolean ontouchevent (Motionevent event) {//modify coordinates Currx = Event.getx (); CurrY = Event.gety ();// Notifies the current component to redraw invalidate (); return true;}}

2) Use Java code to add a custom view to the layout file

  

Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Relativelayout layout = (relativelayout) Findviewbyid (R.id.main); final Drawview draw = new Drawview (this); Layout.addview (Draw);

3) You can also directly introduce a custom Drawview in the layout file

  

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    android:id= "@+id/main    " xmlns:tools= "Http://schemas.android.com/tools"    android:layout_width= "match_parent"    android:layout_ height= "Match_parent"    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@ Dimen/activity_horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android: paddingtop= "@dimen/activity_vertical_margin"    tools:context= "com.examples.drawview.MainActivity" >< Com.examples.drawview.DrawView     android:layout_width= "match_parent"    android:layout_height= "Match_ Parent "/></relativelayout>

Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);

2.1 Android View Components

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.