Day 4-part 4-step 4 of Piglet's Android getting started

Source: Internet
Author: User
Tags gety

Day 4-part 4-step 4 of Piglet's Android getting started

Day 4-part 4-step 4 of Piglet's Android getting started

Android event processing mechanism-collection of event processing mechanisms

------------Reprinted, please specify the source -- coder-pig


This section introduces:

In the first three parts, I have learned about android's event processing mechanism,

The Time Processing Mechanism Based on listening and callback and the mechanism for passing information using Handler have been learned;

In the last part, we will supplement some small knowledge points, such as the two forms of touch events,

The Configuration class and AsyncTask asynchronous task are explained. Now, start the course in this section!



This section describes the road map:





Body:


Touch event


Touch events can be implemented in the following two forms: listener-based and callback-based.

The following is a simple example:



① Listener-based TouchListener

:



The Code is as follows:

Main. xml:

     
  
 


MainAcitivity. java

Package example.jay.com. toufinally; import android. support. v7.app. actionBarActivity; import android. OS. bundle; import android. view. menu; import android. view. menuItem; import android. view. motionEvent; import android. view. view; import android. widget. imageView; import android. widget. textView; import android. widget. toast; public class MyActivity extends ActionBarActivity {private ImageView imgtouch; @ Override prote Cted void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_my); imgtouch = (ImageView) findViewById (R. id. imgtouch); imgtouch. setOnTouchListener (new View. onTouchListener () {@ Override public boolean onTouch (View v, MotionEvent event) {Toast. makeText (getApplicationContext (), "You touch lunjia through the listener mode: OnTouchListener ~ ", Toast. LENGTH_LONG). show (); return true ;}});}}


Code parsing:

You can simply set an ImageView, setOnTouchListener, and rewrite the onTouch method! It's very simple. In fact, this section in the frame layout already has

Example: Cute girl moving with her fingers


Finally, let's talk about some methods and attributes of OnTouchListener:

OnTouch (View v, MotionEvent event): In turn, the parameters here are the components that trigger the touch event and touch the event.

It encapsulates the details of the trigger event, including the event type, trigger time, and other information. For example, event. getX (), event. getY ()

We can also judge the touch action type and use event. getAction () to judge it. For example:

Event. getAction = MotionEvent. ACTION_DOWN, press the event

Event. getAction = MotionEvent. ACTION_MOVE: Move event

Event. getAction = MotionEvent. ACTION_UP: the event is popped up.

Of course, there are also some touch fingers,For more information, see the development documentation, which will not be listed here!






② Callback-based onTouchEvent () method

The same style touch event, but onTouchEvent is mostly used for custom views. This method is overwritten in all view classes, and this kind of touch event is based on callback, that is:

If the returned value is false, the event will continue to be propagated and processed by the external container or Activity! Of course, Gesture is also involved.

I will explain it in detail later! OnTouchEvent is actually similar to onTouchListener, but the processing mechanism is not needed. The former is callback, and the latter is the listening mode!


Simple code example: Small Ball Moving with fingers

Custom View

MyView. java

Package example.jay.com. touch2; import android. content. context; import android. graphics. canvas; import android. graphics. color; import android. graphics. paint; import android. util. attributeSet; import android. view. motionEvent; import android. view. view; public class MyView extends View {public float X = 50; public float Y = 50; // create Paint paint = new Paint (); public MyView (Context context, attributeSet) {super (context, set) ;}@ Override public void onDraw (Canvas canvas) {super. onDraw (canvas); paint. setColor (Color. BLUE); canvas. drawCircle (X, Y, 30, paint) ;}@ Override public boolean onTouchEvent (MotionEvent event) {this. X = event. getX (); this. Y = event. getY (); // The Notification component redraws this. invalidate (); return true ;}}


Main. xml layout file:

     
  
 


Run:

Move with your fingers ~




Respond to system-set events: Configuration class


Use of the Configuration class:

This type is used to describe the configuration information on the mobile phone device, such as the screen direction, touch mode of the touch screen, etc.

Usage:① Obtain the System Configuration object

Configuration cfg = getResources (). getConfiguration ();

② Next, you can obtain the cfg. XXX attribute. Most of them are screen-based judgments, and look up the table if needed.

FontScale:Obtains the scaling factor of the font set by the current user.

Keyboard: gets the keyboard type associated with the current device. Return Value of this attribute: KEYBOARD_12KEY (Keypad with only 12 keys), KEYBOARD_NOKEYS, KEYBOARD_QWERTY (normal keyboard)

KeyboardHidden:This attribute returns a boolean value to identify whether the current keyboard is available. This attribute not only determines the system's hardware keyboard, but also determines the system's soft keyboard (on the screen ).

Locale:Obtain the current Locale of the user.

Mcc: the country code for retrieving mobile Signals

Mnc: gets the mobile signal's network code

Ps: the country code and network code jointly determine the current mobile phone network operator

Navigation:Determine the type of the System navigation device. Return Value of this attribute: NAVIGATION_NONAV (no navigation), NAVIGATION_DPAD (DPAD navigation)

NAVIGATION_TRACKBALL and NAVIGATION_WHEEL)

Orientation:Obtain the System screen direction. Returned value of this attribute:ORIENTATION_LANDSCAPE (landscape screen),ORIENTATION_PORTRAIT (vertical screen)

Touchscreen:Obtain the touch mode of the System touch screen. Returned value of this attribute: TOUCHSCREEN_NOTOUCH (no touch screen), TOUCHSCREEN_STYLUS (touch pen touch screen ),
TOUCHSCREEN_FINGER (touch screen for receiving fingers)




Override onConfigurationChanged to respond to system settings changes


This method is used to listen for system settings changes. It is a callback-based time processing method that is automatically triggered when the system settings change;

Note that the targetSdkVersion attribute can only be set to 12 if the following method is used for monitoring. If the value is higher than 12, this method will not be fired!

The changes to the monitoring system settings will be studied later. Now, you must master this!


Sample Code:

Click a simple button to switch between the portrait and landscape, and then Toast prompts

As follows:



The Code is as follows:

MainActivity. java

Package com. example. configurationchangedemo; import android. app. activity; import android. content. pm. activityInfo; import android. content. res. configuration; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. toast; public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceStat E) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button btn = (Button) findViewById (R. id. btncahange); btn. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Configuration config = getResources (). getConfiguration (); // if the screen is landscape, switch to landscape if (config. orientation = Configuration. ORIENTATION_LANDSCAPE) {MainActivity. this. setRequestedOrientation (ActivityInf O. SCREEN_ORIENTATION_PORTRAIT);} // if the landscape is portrait, switch to landscape if (config. orientation = Configuration. ORIENTATION_PORTRAIT) {MainActivity. this. setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE) ;}}) ;}@ Overridepublic void onConfigurationChanged (Configuration newConfig) {super. onConfigurationChanged (newConfig); String screen = newConfig. orientation = Configuration. ORIENTATION_LANDSCAPE? "Landscape": "Landscape"; Toast. makeText (MainActivity. this, "System screen Direction Changed \ n direction changed to" + screen, Toast. LENGTH_SHORT ). show ();}}

You also need to configure the following AndroidManifest. xml file:

Add the following code to the file:

Permission:

In android: configChanges = "orientation"

SetTargetSdkVersion is changed to below 12Or 12.



AsyncTask asynchronous task


Introduction of AsyncTask:



Related methods:



Note:



Sample Code:

A simple progress bar + button + text box

Because we haven't talked about the network, we use a delay thread to simulate the file download process.

:



Main. xml layout file:

     
      
      
      
  
 






Custom delay thread:

Package example.jay.com. asynctaskdemo; public class DelayOperator {// delayed operation, used to simulate downloading public void delay () {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();;}}}


Custom AsyncTask

Package example.jay.com. asynctaskdemo; import android. OS. asyncTask; import android. widget. progressBar; import android. widget. textView;/*** Created by Administrator on 8/7/2014. */public class MyAsyncTask extends AsyncTask
 
  
{Private TextView txt; private ProgressBar pgbar; public MyAsyncTask (TextView txt, ProgressBar pgbar) {super (); this.txt = txt; this. pgbar = pgbar;} // This method is not running in the UI thread and is mainly used for asynchronous operations. By calling publishProgress () method // trigger onProgressUpdate to operate the UI @ Override protected String doInBackground (Integer... params) {DelayOperator dop = new DelayOperator (); int I = 0; for (I = 10; I <= 100; I ++ = 10) {dop. delay (); publishProgress ( I);} return I + params [0]. intValue () + "";} // This method runs in the UI thread. You can set the UI control @ Override protected void onPreExecute () {txt. setText ("start executing asynchronous thread ~ ");} // In the doBackground method, the publishProgress method is triggered every time it is called. // The method runs in the UI thread, you can operate on the UI control @ Override protected void onProgressUpdate (Integer... values) {int value = values [0]; pgbar. setProgress (value );}}
 


MainActivity. java

package example.jay.com.asynctaskdemo;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;public class MyActivity extends ActionBarActivity {    private TextView txttitle;    private ProgressBar pgbar;    private Button btnupdate;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_my);        txttitle = (TextView)findViewById(R.id.txttitle);        pgbar = (ProgressBar)findViewById(R.id.pgbar);        btnupdate = (Button)findViewById(R.id.btnupdate);        btnupdate.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                MyAsyncTask myTask = new MyAsyncTask(txttitle,pgbar);                myTask.execute(1000);            }        });    }}



Ps: the code examples are all simple examples for reference on the Internet. It should not be a big problem to understand. First, we need to understand the basic principles;

I will conduct in-depth research on projects later ~


Related Article

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.