Making the view interactive view interaction

Source: Internet
Author: User

Drawing a UI is only one part of creating a custom view. you also need to make your view respond to user input in a way that closely resembles the real-world action you're mimicking. objects shoshould always act in the same way that real objects do. for example,
Images shoshould not immediately pop out of existence and reappear somewhere else, because objects in the real world don't do that. Instead, images shoshould move from one place to another.

Users also sense subtle behavior or feel in an interface, and react best to subtleties that mimic the real world. for example, when users fling a UI object, they shocould sense friction at the beginning that delays the motion, and then at the end sense momentum
That carries the motion beyond the fling.

This lesson demonstrates how to use features of the android framework to add these real-world behaviors to your custom view. http://blog.csdn.net/sergeycao

Handle input gestures

Like kerberother UI frameworks, Android supports an input event model. user Actions are turned into events that trigger callbacks, And you can override the callbacks to customize how your application responds to the user. the most common input event in
Android system isTouch, Which triggersonTouchEvent(android.view.MotionEvent). Override this method to handle the event:

   @Override   public boolean onTouchEvent(MotionEvent event) {    return super.onTouchEvent(event);   }

Touch events by themselves are not participant ly useful. modern touch UIS define interactions in terms of gestures such as tapping, pulling, pushing, flinging, And zooming. to convert raw touch events into gestures, Android provides
GestureDetector.

ConstructGestureDetectorBy passing in an instance of a class that implements
GestureDetector.OnGestureListener. If you only want to process a few gestures, you can extend
GestureDetector.SimpleOnGestureListenerInstead of implementing
GestureDetector.OnGestureListenerInterface. For instance, this Code creates a class that extends
GestureDetector.SimpleOnGestureListenerAnd overrides
onDown(MotionEvent).

class mListener extends GestureDetector.SimpleOnGestureListener {   @Override   public boolean onDown(MotionEvent e) {       return true;   }}mDetector = new GestureDetector(PieChart.this.getContext(), new mListener());

Whether or not you useGestureDetector.SimpleOnGestureListener, You must always implement
onDown()Method that returnstrue. This step is necessary because all gestures begin with
onDown()Message. If you returnfalseFrom
onDown(),GestureDetector.SimpleOnGestureListenerDoes, the system assumes that you want to ignore the rest of the gesture, and the other methods
GestureDetector.OnGestureListenerNever get called. The only time you shoshould return
falseFromonDown()Is if you truly want to ignore an entire gesture. Once you 've implemented
GestureDetector.OnGestureListenerAnd created an instance
GestureDetector, You can use yourGestureDetectorTo interpret the touch events you receive in
onTouchEvent().

@Overridepublic boolean onTouchEvent(MotionEvent event) {   boolean result = mDetector.onTouchEvent(event);   if (!result) {       if (event.getAction() == MotionEvent.ACTION_UP) {           stopScrolling();           result = true;       }   }   return result;}

When you passonTouchEvent()A touch event that it doesn' t recognize as part of a gesture, it returns
false. You can then run your own custom gesture-detection code.

Create physically plausible Motion

Gestures are a powerful way to control touchscreen devices, but they can be counterintuitive and difficult to remember unless they produce physically plausible results. A good example of this is
FlingGesture, where the user quickly moves a finger should ss the screen and then lifts it. this gesture makes sense if the UI responds by moving quickly in the ction of the fling, then slowing down, as if the user had pushed on a flywheel and set
It spinning.

However, simulating the feel of a flywheel isn't trivial. A lot of physics and math are required to get a flywheel model working correctly. fortunately, Android provides helper classes to simulate this and other behaviors. the
ScrollerClass is the basis for handling flywheel-style
FlingGestures.

To start a fling, callfling()With the starting velocity and the minimum and maximum x and y values of the fling. For the velocity value, you can use the value computed for you
GestureDetector.

@Overridepublic boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {   mScroller.fling(currentX, currentY, velocityX / SCALE, velocityY / SCALE, minX, minY, maxX, maxY);   postInvalidate();}

Note:Although the velocity calculated
GestureDetector
Is physically accurate, please developers feel that using this value makes the fling animation too fast. It's common to divide the X and Y velocity by a factor of 4 to 8.

The callfling()Sets up the physics model for the fling gesture. Afterwards, you need to update
ScrollerBy callingScroller.computeScrollOffset()At regular intervals.
computeScrollOffset()UpdatesScrollerObject's internal state by reading the current time and using the physics model to calculate the X and Y position at that time. Call
getCurrX()AndgetCurrY()To retrieve these values.

Most views passScrollerObject's X and Y position directly
scrollTo(). The piechart example is a little different: it uses the current scroll y position to set the rotational angle of the chart.

if (!mScroller.isFinished()) {    mScroller.computeScrollOffset();    setPieRotation(mScroller.getCurrY());}

TheScrollerClass computes scroll positions for you, but it does not automatically apply those positions to your view. It's your responsibility to make sure you get and apply new coordinates often enough to make the scrolling
Animation look smooth. There are two ways to do this:

  • CallpostInvalidate()After callingfling(), In order to force a redraw. This technique requires that you compute scroll offsets in
    onDraw()And callpostInvalidate()Every time the scroll offset changes.
  • Set upValueAnimatorTo animate for the duration of the fling, and add a listener to process animation updates by calling
    addUpdateListener().

The piechart example uses the second approach. this technique is slightly more complex to set up, but it works more closely with the animation system and doesn't require potentially unnecessary view invalidation. the drawback is that
ValueAnimatorIs not available prior to API level 11, so this technique cannot be used on devices running Android versions lower than 3.0.

Note: ValueAnimatorIsn't available prior to API level 11, but you can still use it in applications that target lower API levels. You just need to make sure to check the current API level at runtime,
And omit the callto the view animation system if the current level is less than 11.

       mScroller = new Scroller(getContext(), null, true);       mScrollAnimator = ValueAnimator.ofFloat(0,1);       mScrollAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {           @Override           public void onAnimationUpdate(ValueAnimator valueAnimator) {               if (!mScroller.isFinished()) {                   mScroller.computeScrollOffset();                   setPieRotation(mScroller.getCurrY());               } else {                   mScrollAnimator.cancel();                   onScrollFinished();               }           }       });
Make your transitions smooth

Users expect CT a modern UI to transition smoothly between States. UI elements fade in and out instead of appearing and disappearing. Motions begin and end smoothly instead of starting and stopping abruptly. Android
Property animation framework, introduced in Android 3.0, makes smooth transitions easy.

To use the animation system, whenever a property changes that will affect your view's appearance, do not change the property directly. Instead, use
ValueAnimatorTo make the change. In the following example, modifying the currently selected pie slice in piechart causes the entire chart to rotate so that the selection pointer is centered in the selected slice.
ValueAnimatorChanges the rotation over a period of several hundred milliseconds, rather than immediately setting the new rotation value.

mAutoCenterAnimator = ObjectAnimator.ofInt(PieChart.this, "PieRotation", 0);mAutoCenterAnimator.setIntValues(targetAngle);mAutoCenterAnimator.setDuration(AUTOCENTER_ANIM_DURATION);mAutoCenterAnimator.start();

If the value you want to change is one of the baseViewProperties, doing the animation is even easier, because views have a built-in
ViewPropertyAnimatorThat is optimized for simultaneous animation of multiple properties. For example:

animate().rotation(targetAngle).setDuration(ANIM_DURATION).start();

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.