Custom Control Basics 01_ Menu Wheel __viewpager_ dropdown box _ Custom Switch

Source: Internet
Author: User
Tags transparent color set background

1, custom control categories :

1.1 combined Controls : combined with wirelessly native controls , to match the effects of animations

1.2 A custom control

1.3 Combo Control case Demo :

Case study : Youku Menu demo

Three-layer ring, press the menu key will disappear in the interface by the animation effect, click the small House and Middle circle, the outermost circle disappears

① Layout implementation:

Three layers of relative layout overlay each other (because the picture background is transparent, so you can overlay the display)

Since three layouts are superimposed, this menu option uses a ImageButton control that has a strong focus (otherwise it may not be clicked)

Background= "@android: color/transparent"//Transparent Color on control

② animation effects, three-level menu hiding and display

Animation effect, click on Level Two menu, level three menu rotation disappears, click again to rotate back display

Each layer is actually a square (the ring in a transparent square on the background), so long as it does its own rotation, it can play the rotation of the ring to achieve the animation, from the interface disappears, that is, the center of the bottom of the left rotation of 180 degrees, from the interface, that is, the center of the bottom is centered to the right 180 degrees .

Am.setfillafter ()//settings control remains at the end of the animation state

Am.setstartoffset ()//Set delay to perform animation

The primary menu is to control the level two menu, if the level three menu is also in control, the level three menu disappears, and the two-level menu delay disappears. But clicking on the first menu again does not return a level three menu.

Click the menu button, three menus all disappear, delay order

③ Extra: The animation is finished, the ring is hidden, but can also be clicked, the Settings button is not available when performing the hidden

Setenable ()//Whether the settings are available

When the animation is not finished, clicking again terminates the unfinished animation, so when you perform a hidden or displayed animation, set a listener to run the next animation if the animation is finished (define a variable to control the number of playback animations)

1.4 Viewpager android3.0 Version already contains this control (achieve picture carousel effect)

The Support-v4.jar package contains the Viewpager control, which can be used by the lower version.

When developing in the low version, import Viewpager, copy the full class name using the control (like a custom control)

Color in the layout file #66 (transparency) (R) (G) (B)

Viewpager usage

① Create the number of ImageView as needed, populate the data, set the picture

②viewpager.setadapter (Pageradapter)//set the corresponding adapter on the line

If the adapter class parameter name exception (ARGXX) need to import the source code (if you do not find the import source after the class button, uninstall the V4 package re-add, you can import the source code)

Source Path Sdk/extras/android/support/v4/src/java

Several important methods in the adapter class

GetCount ()//number of entries returned

Isviewfromobject (XX,XX)//To determine whether to use the cache, if the return is true, use the cache, do not call the Instantixx method to create a new object,

Simply put: If the user does not slide out of bounds, the picture object does not change, and if an object needs to be reinitialized to display.

Return value recommended notation view==object//if it is an object, use the cache, if not create a new

Instantiateitem ()//Initialize an entry

Preload feature: Both left and right images are pre-loaded, that is, two images are initialized

Initializes an entry to add the position corresponding ImageView to the Viewpager

Viewpager.addview (Imageviewlist.get (position));

return to this view;

Destoryitem ()//Destroy an entry, position the currently destroyed index

Remove the ImageView from the Viewpager

Viewpager.removeview (Imageviewlist.get (position));

Additional: If there is no method found, but the project does have a jar package, to check the configuration build path, Hook can

Implementation of the progress point and picture Description array of 1.4.2 Picture carousel

① in the loop to add the picture, but also to the progress point corresponding to the parent control to add a small point, the development of the art to do, here through the XML.

Creation of small dots

Creating an XML file for a shape node

Shape properties: shape= "oval"//Round

Sub-node corners//Radian 5DP

Solid//Fixed color

Remember to create two, one with focus, one without focus

② when adding, remember to set the corresponding parameter setting width height

View v = new (this)

V.setbackgxxxxx (ID);

Layoutparams params = new xxxx (W,H)//Set wide height

params.xxxx//can set the corresponding parameters, the distance between the controls, whether the setting is selected (setting a state selector can achieve the effect of switching the progress of small dots)

V.setlayoutparams (params);//Set parameters, you must set parameters, otherwise you cannot display

Last added into the linerlayout

③ The data index of the picture description information to match the picture data on the adapter

Extra: Set the default check point, note the order of the Code, and set it after the data is set.

④ change Progress point status and information display based on Viewpager toggle State

Viewpager.setonpagechangelistener (this)//set page Toggle Listener

Two methods

Onpageselected ()//When the page is selected (fully displayed), this method is triggered

Change the child node collection of the Progress Point parent node child (status of Progress Point)

Change the display of text descriptions

Do not forget to modify the state of the previous node (take a reference to record it, if position directly +--words, easy logic confusion)

Onpagescrolled ()//call when the page is curled

1.4.3 pseudo Infinite loop and dynamic switching

①viewpager moves to the first (0) or the last (maximum index),

The previous (-1) or Next (maximum index + 1) is not preloaded

So, let's get the count back large (like 2g-1 (Integer.max_value)) (Math tips).

Then the corresponding index is the count% set length//equivalent to the multiple of the remainder, can be corresponding to the specified index

Extra: When initializing, the default selected point is the value of the middle of the returned count (so that there is no stagnation blocking the slide), to let the selected point in the first position, let the middle value minus the multiplier to take the remainder

Pageview.setcurrentitem ()//Set the default selected coordinates

Extra: Set the default check point, actually call the Onpageselected () method, remember to change the position of the previous point and the current point settings, because at the beginning such two are 0, so you want to set to be selected later. The previous setting is unchecked.

② Dynamic Switching

Turn on a sub-thread and periodically switch Viewpager's picture (this is an action to modify the UI).

Note, however, that the child thread is not destroyed directly in the activity, and the activity's Ondestory () method sets a variable to control the infinite loop

Extra: The hibernation operation is put into the loop at the end, it will not be output more once (because when the variable is controlled, it will be output more once, so this is a small optimization)

2 Combo Control: drop-down selection box (ListView Fill), Reference effect:

2.1 Reference layout:

Click the down arrow, the drop-down box appears, click the dropdown box option will fill the corresponding number into the input box

The drop-down box is actually Popupwindow, and the content is a ListView

Set up an adapter to populate the data

Add the ListView to the Popupwindow

Popupwindow pw = new Popupwindow (listview,w,h);

W: Width: The width of the input box, et.getwidth ();

H; height: The whole screen can be set to death.

displayed on the interface, displayed under a control

Pw.showasdropdown (input box, offset x, offset y)

2.2 Detail Questions

① outline Border is the background picture of the ListView

②listview.setverticalscrollbarenable ()//Set whether the right vertical slide bar is displayed

If all the entries have been deleted, you should close the popup.

③button,imagebutton,checkbox this kind of control grab the focus ability is very strong.

Popupwindow itself is not able to use focus, setting can use focus, does not take effect

Cause: The button or ImageButton of the child item took the focus away.

Sets the child control to not preempt events of the parent element, but can allocate events as blocks

Workaround: Give the child entry LinearLayout layout: descendantfocusablity= "Blocksdescxxx"

There is a slight gap between the ④popupwindow and the input box.

Because the input box itself has a border width, and the width of the input box is not included, a little bit less is fine.

⑤ Click anywhere else to let it be closed

Popupwindow.setoutsidetouchable ()//Click outside can be closed, separate settings do not take effect

Popupwindow.setbackground (XXXX)//Set a background for the above settings to take effect

3. Custom controls (grouped controls are preceded)

3.1 Slide switch, reference, drag the block can switch

① Android Each control or layout inherits from the view class (the control's father), creating a class to inherit the view

Construction methods that need to be overridden

If you want to new in Java, rewrite only the context constructs

If you want to reference a custom control in a layout file, use a construct with a context and Atts

Generally two are written.

② Copy the corresponding picture

The creation method (all public, caller customizable, and from this perspective the implementation of the custom control feature),

Set background picture Setswitchbackgorundresource ()//The name is easier to understand,

To set a picture of a slider

Sets the default state of the current switch.

Use the corresponding member variables to record them, so that they are easy to handle when drawing.

③ Drawing of custom controls

The drawing process for view in Android

Do not go directly to overwrite, using the callback interface provided by Google

Measure (measure width and height information) >>>layout (layout/layout, including child controls) >>>draw (Drawing)

Onmeasure (called when measured) >>>onlayout (callback at layout time) >>>ondraw (when drawing)

3.2 Drawing controls

① measure and set its own width and height in the Onmeasure method

Overriding the Onmeasure (XXX) method

Set the width and height of the background picture to match

Setmeasuredimension (w,h);//Setting the width and height after measurement

Super.xxx to be at the front, otherwise it won't take effect.

② does not have child controls and does not require a onlayout callback to draw the switch in the OnDraw () method

Rewrite OnDraw (Canvas) method, Super.ondraw ()//Can be deleted

Canvas artboards, what you draw with canvas, are displayed on the screen as the current control

Tile the background image on the current control

Canvas.drawbitmap (picture, left, top, brush)//0,0 (upper left), null (no brushes required for drawing pictures)

Draw slider State based on current state currentstate (member variable)

If true, draws to the right of the background picture (the left margin is the background width minus the switch width, and the top margin is 0 on the front)

If False, draws to the left of the background picture (the left margin is 0 and the top margin is 0)

3.3 Touch Move Change status

① rewrite ontouchevent ()//return value is true consumes the current event, handles itself, returns false to others to handle.

② Judging Event Types

Observation shows that only the x-axis values are changed when moving

Record the point that is pressed, the point at which you move, and the x-axis value of the two is the displacement range (positive to left and negative to right).

If you use this approach, you need to record the initial position and then modify it.

In fact, you can set the value of the left margin directly with the moving point value.

Manually trigger the redraw of the OnDraw method when the moving point changes.

Invaliadte ()//refreshes the current control, causing a call to the OnDraw method.

③ in the OnDraw () method, dynamically modifies the position of the slider according to the value of the x-axis

Canvas.drawbitmap (slider picture, left margin, 0 top margin unchanged, NULL does not need a brush);

3.3.2 User Experience issues

① will move out of the boundary.

Limit width, the left margin of the slider must not be less than 0, if less than 0, the drawing is always set to 0

The left margin (the left margin of the slider) also cannot be greater than (the width of the background image-the width of the slider),

If it is greater, it is always the difference between the two.

When the ② is moved, it is not automatically returned if it is loosened in the middle.

The first thing to know is whether you are sliding (or you will be jumping directly when you swipe).

When released (set to not sliding), determines the state based on the value of the left margin

If you are not sliding, the two methods

(Determines whether the left margin of the slider is greater than One-fourth of the entire background image,

If the greater than is on behalf of the user wants to close it, if less than on behalf of the user wants to turn it on. Based on results

(or the center point of the slider and the center point value of the background picture,

If the slider center point > Background Picture Center point value, the current state resets to true, the state of the Open

If it is less than, reset to false, the state of the shutdown

)

③ finger presses the position is not the same as the user expected (the user wants to move the point is the middle point, and actually the point is pressed)

When redrawing, the left margin values >> adjustments >> left margin minus half the width of the slider.

Finally, this data is judged.

Custom Control Basics 01_ Menu Wheel __viewpager_ dropdown box _ Custom Switch

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.