Interface activity interactive response of Android system programming introduction series


stayLast articleThe interface has been learned inActivityThe drawing of depends entirely on the view component it loadsViewNot only that, each touch operation of the user can be displayed on the interfaceActivityReceive and respond within, or directly transfer to one of the viewsViewResponse. How should the user respond to the user’s operation? Does the same operation act on the interface or a sub view in the interface? In view of the different interaction modes generated by the user’s operation objects, this paper will introduce them respectively.

Intra interface interaction

Interface response

When it comes to interface interaction, it is easy to think of the user’s touch operation on the device screen. But how do you determine where the user touches when the screen is so large? The Android system defines a set ofScreen coordinatesThe rule is not only applicable to the current screen interaction, but also applicable to the animation drawing and other screen related operations mentioned later. This rule takes the upper left corner of the screen as theOrigin of screen coordinates, the direction extending from the upper left corner to the upper right cornerX axis of screen coordinatesAs the direction extending from the upper left corner to the lower left cornerY-axis of screen coordinates

For example, for a 1024×512 TV device, the bottom left cornerScreen coordinatesThe value is (0, 512), in the lower right cornerScreen coordinatesThe value is (1024, 512), and the value in the upper right corner isScreen coordinatesThe value is (1024, 0), and the value in the upper left corner isScreen coordinatesThe value is (0, 0).

With a measurement standard for the touch position of the screen, can you do touch operation according to different positions? When it comes to touch operation, it also needs to be processed separately after refinement. The Android system roughly divides user operation behaviors into three types:Press behaviorSliding behaviorLift release behavior。 In this way, the system can make separate response processing according to each operation behavior.

In addition, in addition to the hardware device screen mentioned above, the user’s operation object also has the keys of the hardware device (including hardware keys and virtual keys). But the operation behavior of keys is onlyPress behaviorandLift release behaviorTwo, and the key operation does not need to be usedScreen coordinatesRelevant contents.

Based on the above introduction, you can use the interfaceActivityThe following three methods can be rewritten to respond to user interface operation interaction.

  • boolean onTouchEvent(MotionEvent event)
    When the sub view is not processed, the user will call back this method once for each operation on the hardware device screen.

    Its parametersandroid.view.MotionEventThe instantiation object event of the event class.
    event.getAction()Method to get the current event behavior, includingMotionEvent.ACTION_DOWNPress behaviorMotionEvent.ACTION_MOVESliding behaviorMotionEvent.ACTION_UPLift release behaviorWait.
    event.getX()Method to get the of the current operationScreen coordinate X axisValue.
    Similarlyevent.getY()Method to get the of the current operationScreen coordinate y-axisValue.

  • boolean onKeyDown(int keyCode, KeyEvent event)
    When the subview is not processed, every time the user presses a key on the hardware devicePress behavior, the method will be called back once.

    Parameter 1 keycode of int type specifies the key type, and its value is generally the same as parameter 2event.getKeyCode()equal.
    Parameter twoandroid.view.KeyEventClass.
    event.getAction()Method can also get the current event behavior, onlyKeyEvent.ACTION_DOWNPress behaviorandKeyEvent.ACTION_UPLift release behaviorTwo behavior values.
    event.getKeyCode()Method can obtain the key type that triggers the current event, and its values includeKeyEvent.KEYCODE_HOMEHome keyKeyEvent.KEYCODE_POWERPower keyKEYCODE_VOLUME_UPVolume increase keyWait.

  • boolean onKeyUp(int keyCode, KeyEvent event)
    When the subview is not processed, every time the user presses a key on the hardware deviceLift release behavior, the method will be called back once. Its two parameters are the same as those aboveonKeyDown()The two parameters in are similar.

View response

Relatively speaking, the view response in the interface is more cumbersome, and the effect can be more diversified. When the viewViewAs the user’s operation object, you can still override the three methods of the above interface response, butSystem viewIt often encapsulates a more simple and crude response method.

After rewriting the three methods of the interface response in the view, if the returned result is true, the three methods in the above interface response will not be recalled.

There are two code implementations for rewriting the three methods in the interface response. One is for defined viewsViewClass by calling setOnTouchListener (View.OnTouchListener l)And other monitoring methods, just implement the relevant response method in the monitoring class. Or the defined viewViewAs a parent class, recreate a custom viewView, in the new customizationViewYou can override the relevant response method directly in the, and use the original view in the declarationViewClass, modify to use the new customViewClass. Usually for statements thatfinalA class can only be implemented using mode 1.

stayView.OnTouchListenerClassonTouch(View v, MotionEvent event)Method takes precedence over the viewViewInternalonTouchEvent(MotionEvent event)Called, so ifonTouch(View v, MotionEvent event)If the returned result is true, the view will not be recalledViewInternalonTouchEvent(MotionEvent event)And the viewViewOther internal response interaction class listeners (such as setonclicklistener (view. Onclicklistener L), setonlongclicklistener (view. Onlongclicklistener L), etc.) will not be called.

Why encapsulate a layer of response methods? The user’s operation on the view is oftenclick(to be executed in a short time)Press behaviorandLift release behavior),Long press(in execution)Press behaviorWait for a period of time before executingLift release behavior),Drag(in execution)Press behaviorExecute the next paragraphSliding behaviorThen executeLift release behavior)These fixed operation types. If each view needs to subdivide the user’s operation behavior, there will be a large number of redundant operation type judgment codes, so the Android SDK defines a series of interfaces corresponding to the user’s operation types. If a view needs to respond to an operation, it only needs to set the instantiated object of its operation type interface and implement the relevant methods in the object. These interfaces mainly include the following three.

  • View.OnClickListenerInterface
    Need to implementonClick(View view)Method within which to respond to the response viewViewBy userclickCode logic after.
  • View.OnLongClickListenerInterface
    Need to implementonLongClick(View view)Method within which to respond to the response viewViewBy userLong pressCode logic after.
  • View.OnDragListenerInterface
    Need to implementonDrag(View v, DragEvent event)Method within which to respond to the viewViewBy userDragCode logic after.

In addition, differentSystem viewThere may also be separately set response methods, or the user-defined view will also provide separate response methods, such as how to respond after a row of data in the list view is clicked separately. These should be found and used according to the specific view class, which will not be repeated here.

Event delivery mechanism

Among the three interface response methods mentioned above, the precondition for their callback time is that the sub view is not processed, that is, the return result of the interface response method of the sub view is false. This involves the event delivery mechanism of Android system.
We know the interfaceActivityCalled after creationsetContentView(int layoutId)Load root viewViewIn the root view, you can embed layers of child views. Then, if the user touches his finger on the screen, it will triggerPress behavior, this behavior is first passed to the root view as an event, then the root view passes the event to the child view, and the child view passes the event to the child view of the child view. In this way, events are passed layer by layer according to the nesting order during loading, which is calledEvent distribution
Until the event is passed to the last layer of child view, or a layer view does not continue to pass the event, the event will be processed first in the last layer view. After receiving the passed in event, each layer view has two ways to choose, either continue to pass the event to the child view or handle the event by itself. If you choose the second way to handle the event by yourself instead of continuing to pass the child view, it is calledEvent interception
Once a layer view processes the event, its parent layer view will continue to process the event, and then the parent layer view of the parent layer will process the event. The event is processed at such a layer until the root view processes the event, which is calledevent processing
After going throughEvent distributionandevent processing After that, such an event delivery mechanism is completed. This is true for every event mentioned above.

The implementation of the above process in the code only needs to be specific toEvent distributionEvent interceptionandevent processing Define a rewritable method respectively. The main places where this method can be overridden toEvent interceptionIt only occurs during the transfer of child views and is not required in the interface, soEvent interceptionThe corresponding method is only inandroid.view.GroupViewOverridden in.

  • boolean dispatchTouchEvent (MotionEvent event)
    When an event is distributed to the view, the system calls back the method in the view. The returned result indicates whether the current event has been processed.
  • boolean onInterceptTouchEvent(MotionEvent event)
    When an event is distributed to the view, the system will call back the method in the view to determine whether to intercept the event and hand it over to the current view for processing according to the returned result. The default return result is false, which means that the event will not be intercepted and will continue to tune back to the subviewdispatchTouchEvent()。 When the return result is true, it means that the event is intercepted and the current view will be recalledonTouchEvent().
  • boolean onTouchEvent (MotionEvent event)
    When it is the view’s turn to process an event, the above event distribution method will be displayed in the viewboolean dispatchTouchEvent (MotionEvent event)Callback to the method in. The returned result indicates whether the current event has been processed.

Interface interaction

For one interface, described aboveActivityInteractive response, then two interfacesActivityHow do they interact? This is used inLoading interfaceStart in a textActivityUsedandroid.content.IntentIntention class. Different from the interaction between users and interfaces, the interaction between interfaces is mainly the sharing of variable dataIntentThe supported interactive data types are limited.

Send data interface

Start an interface atActivityCreate an intent object before callingputExtras(Bundle bundle)Method, you can package the data to be sent intoandroid.os.BundleAn instance of type.

And thatBundleSupport for the types of data objects can store includesbooleancharbyteshortintfloatdoublelongEight basic data types,StringType and ImplementationParcelableAny type of interface, and[]Array orArrayListArrays, and other unusual types. These data are saved in the form of key value pairsBundleObject. For different data types to be saved, call the correspondingputT(String key, T value)A series of methods can be stored in the form of parameter 1 key and parameter 2 value, and the corresponding methods can also be calledgetT(String key)A series of methods take out the value data corresponding to a key of the specified parameter. T here generally refers to different data types supported.
In addition, it can also be called directly in the created intent objectputExtra(String key, T value)A series of methods, which store the data to be sent directly in the form of key value pairs, can also be usedgetTExtra(String key)A series of methods take out the value data corresponding to a key of the specified parameter. T here also refers toBundleDifferent data types that can be supported.

After all the data is packaged, it can be displayed in the current interfaceActivityContinue calling instartActivity(Intent intent)Series method startIntentAnother interface specified in the intent parameterActivityYes.
therestartActivity(Intent)Method is the simplest startup method. In addition, there arestartActivity(Intent, Bundle)At startup, the data to be sent is packaged and passed in as parameter 2.
perhapsstartActivityForResult(Intent intent, int requestCode)During startup, a unique value is passed as parameter 2 to distinguish the intention of starting different interfacesActivityAfter returning, the system will call the current interfaceActivityMediumonActivityResult(int requestCode, int resultCode, Intent data)Method, so you can override it. According to the uniqueness of parameter 1, different interface intentions started before are distinguished. Parameter 2 is the result value returned according to different closing statuses of the startup interface. The default value,, its value needs to be set when the startup interface returns. Parameter 3 is returned from the startup interfaceIntentType, mainly usingBundlePackage data type objects. Similarly, their values can be set when the startup interface returns.

Receiving data interface

As the startup interface for receiving dataActivity, after its binding context environment, it is generallyonCreate(Bundle savedInstanceState)Method, you can usegetIntent()Method to get the passed inIntentIntention object. After obtaining the object, it can be passed naturallygetBExtras()Or a series ofgetTExtra(String key)Get the packaged data, so that the previous interface before startup can be used in the startup interfaceActivtiyVariable data in.

And when you start the interfaceActivityWhen returned by user operation, the system will call back the start interfaceonBackPressed()Method, and thenActivityRemove from stack and destroy. So it can be rewrittenonBackPressed()Method is invoked in this method.setResult(int resultCode, Intent data)Set the return time parameters mentioned above.
Or in the startup interfaceActivityCode can also be actively calledfinish()Method to close the current interface. So when you callfinish()MethodsetResult(int resultCode, Intent data)Set the return parameters.