[Android] Custom controls

Source: Internet
Author: User
Tags getcolor

Some of the fixed controls and properties may not meet the development requirements during Android app development, so in some special cases we need to customize the controls and properties.

First, the implementation of steps

1. Inherit the view class or its subclasses

2. Some functions in the replication view

3. Add attributes to the Custom view class (two ways)

4. Drawing controls (importing layouts)

5. Responding to user events

6. Define callback functions (choose according to your needs)

Second, which methods need to be rewritten
    • OnDraw ()

      OnDraw () In view is an empty function, which means that the specific view will overwrite the function to achieve its own drawing. For ViewGroup, you do not need to implement this function, because as a container is "no content" (but you must implement the Dispatchdraw () function, telling the child view to draw itself).

    • OnLayout ()

      Mainly for ViewGroup type layout sub-view, in view this function is an empty function.

    • Onmeasure ()

      The way to calculate the view size (that is, length and width) and save the calculation results by setmeasureddimension (width, height).

    • Ontouchevent

      Defines touch-screen events to respond to user actions.
        

There are some less common ways to do this:

OnKeyDown when a keyboard is pressed

OnKeyUp when you release a keyboard
  
Ontrackballevent when a trackball event occurs
  
Onsizechange () When the size of the component is changed
  
Onfinishinflate () callback method that is called when the application is loaded from XML and used to build the interface with it
  
Onwindowfocuschanged (Boolean) When the component gets, loses focus
Onattachedtowindow () When the component is placed in a window
  
Ondetachedfromwindow () The method that is triggered when the component is detached from a window
  
onwindowvisibilitychanged (int): The method that fires when the visibility of the window that contains the component has changed

Three. Three ways to customize a control

1. Inherit existing controls

When you want to implement a control that is similar to an existing control in many ways, it satisfies the requirements by extending the existing controls.

2. Inherit a layout file

Typically used to customize a composite control, the layout file of a custom control is loaded in the constructor with the Inflater and AddView () methods to form a graphical interface (no OnDraw method is required).

3. Inherit view

The component interface is drawn through the OnDraw method.

Four. Two ways to customize attributes

1. Add attributes directly to the layout file and get them in the constructor.

Layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    >     <com.example.demo.myView         android:layout_width="wrap_content"         android:layout_height="wrap_content"          Text="@string/hello_world"         /></RelativeLayout>

Get property value:

publicmyView(Context context, AttributeSet attrs) {        super(context, attrs);        // TODO Auto-generated constructor stubint textId = attrs.getAttributeResourceValue(null"Text"0);String text = context.getResources().getText(textId).toString();    }

2. Create a attrs.xml under Res/values/to declare the properties of your custom view.

The properties that can be defined are:

<declare-styleable name ="Name">//Refer to a resource ID (name can be arbitrarily named)<attr name ="Background" format="Reference"/>//Color values<attr name ="TextColor" format="Color"/>//Boolean value<attr name ="Focusable" format="Boolean"/>//Dimension value<attr name ="Layout_width" format="Dimension"/>//floating-point value<attr name ="Fromalpha" format="Float"/>//Integer value<attr name ="Frameduration" format="integer"/>//String<attr name ="Text" format="string"/>//Percentage<attr name ="Pivotx" format="Fraction"/>//enumeration value<attr name="Orientation"> <enum name="Horizontal" value="0"/> <enum name="Vertical" value="1"/> </attr>//bit or arithmetic<attr name="Windowsoftinputmode"> <flag name ="Stateunspecified" value="0"/> <flag name ="Stateunchanged" value="1"/> </attr>//multi-type<attr name ="Background" format="Reference|color"/> </declare-styleable>
    • Attrs.xml to attribute declarations

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <declare-styleable name="MyView">        <attr name="text" format="string"/>        <attr name="TextColor" format="Color"/>    </declare-styleable></Resources>
    • Add to Layout file

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"  android:layout_width= android:layout_height=" match_parent " xmlns:myview=" Http://schemas.android.com/apk/com.example.demo " > <com
      .example  .demo  .myview  android:layout_width=" wrap_content " and Roid:layout_height= "wrap_content"  myview:text =  "test"  myview:textcolor = "#ff0000" /></relativelayout>  pre>

Notice the namespace here:
xmlns: prefix = "http://schemas.android.com/apk/res/package name (or Res-auto)",

Prefix: textcolor use attributes.

    • Get the property value in the constructor

Public MyView (context context, AttributeSet Attrs) {Super (context, attrs);TODO auto-generated constructor stub TypedArray A = Context. Obtainstyledattributes(Attrs, R. Styleable. MyView); String Text = a. getString(R. Styleable. MyView_text); int textcolor = A. GetColor(R. Styleable. MyView_textcolor, Color. White); A. Recycle();}

Or:

     Public MyView(context context, AttributeSet attrs) {Super(context, attrs);//TODO auto-generated constructor stubTypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.myview);intn = a.getindexcount (); for(intI=0; i<n;i++) {intattr = A.getindex (i);Switch(attr) { CaseR.styleable.myview_text: Break; CaseR.styleable.myview_textcolor: Break;    }} a.recycle (); }
Five. Customize the ball that moves with your finger (small example)

To achieve the above effect, we need to divide these steps roughly.

    • Create a attrs.xml under Res/values/to declare the properties of your custom view
    • A class of custom view that inherits the view and the partial function of the replication
    • A container interface for displaying custom view

1. The custom view is named MyView, which has a property value in the format color,

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="myView">        <attr name="TextColor" format="color"/>    </declare-styleable>        </resources>

2. In the constructor get the property configuration of the view and the replication OnDraw and Ontouchevent functions to implement the drawing interface and user event response.

 Public  class myView extends View{    //define brush and initial positionPaint p =NewPaint (); Public floatCurrentX = -; Public floatCurrentY = -; Public intTextColor; Public MyView(context context, AttributeSet attrs) {Super(context, attrs);//Get the attribute in the resource file, because there is only one attribute value, do not traverse the array, take out the color value directly from the R file        //Put attributes in the resource file for easy setup and reuseTypedArray array = context.obtainstyledattributes (Attrs,r.styleable.myview);        TextColor = Array.getcolor (R.styleable.myview_textcolor,color.black);    Array.recycle (); }@Override    protected void OnDraw(Canvas canvas) {Super. OnDraw (canvas);//Draw a blue circleP.setcolor (Color.Blue); Canvas.drawcircle (Currentx,currenty, -, p);//Set text and color, here the color is the value inside the resource file valuesP.setcolor (TextColor); Canvas.drawtext ("by Finch", currentx- -, currenty+ -, p); }@Override     Public Boolean ontouchevent(Motionevent event)        {CurrentX = Event.getx ();        CurrentY = Event.gety (); Invalidate ();//Redraw graphics        return true; }}

Here, by constantly updating the current position coordinates and redrawing the graphics to achieve the effect, pay attention to the use of Typedarray must remember recycle (). Doing so will have an impact on the next call.
   

3. Add the MyView to the Activity_main.xml layout

<?xml version= "1.0" encoding= "Utf-8"?><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"    Xmlns:myview="Http://schemas.android.com/apk/res-auto"    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="Finch.scu.cn.myview.MainActivity">    <finch.scu.cn.myview.myViewandroid:layout_width="Match_parent"android: Layout_height="Match_parent"myview:textcolor="#ff0000" />                        </relativelayout>

4. And finally the mainactivity.

publicclass MainActivity extends AppCompatActivity {    @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }}
    • Specific view to be based on specific needs, such as we want to slide off the listview we can inherit the ListView, listen to the slide event, display Delete button implementation.

[Android] Custom controls

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.