Tips for Android Development

Source: Internet
Author: User

Tips for Android Development

1. Hide the Activity title

1. Code setting: In the onCreate () method

RequestWindowFeature (Window. FEATURE_NO_TITLE );

2. Set in manifest. xml

Android: theme = "@ android: style/Theme. NoTitleBar"

Ii. Input Context instance in Toast

Toast in Activity, use this to return a Context instance

Toast is used in AlertDialog. Therefore, the getApplicationContext () method is used to return a Context instance.

Note:

TextView TV = new TextView (this );

When creating a View object, the input parameter is the Context object. Because the Activity class is a subclass of the Context class, this keyword can be used to represent this Context object.

3. A difference between Activity and Fragment

When the Activity enters the day after tomorrow, it will be placed in the back stack. In this way, when you press the Back key, the Activity can be restored. However, Fragment will not be automatically put into the back stack when it enters the background. To achieve this goal, the addToBackStack () method is displayed during Fragment processing.

For example:

FragmnetManangermanager = getFragmentManager ();

FragmentTransactionfragmentTransaction = fragmentMananger. beginTransaction ();

FragmentTransaction. replace (android. R. id. content, myfragment );

FragmentTransaction. addToBackStack (null );

FragmentTransaction. commit ();

This Code ensures that when Fragment is added to the Activity, you can click the Back button to remove it.

4. Intent calls the system application and uses startActivity (intent) to jump to the page

1. Browser

Intent intent = new Intent (android. content. Intent. ACTION_VIEW, Uri.

Parse ("http://www.baidu.com "));

Selector (optional)

Startatiser (Intent. createChooser (intent, "selectBrower .."));

2. Call

Intent intent = newIntent (android. content. Intent. ACTION_DIAL, Uri.

Parse ("tel: + 3444444 "));

To allow an application to call a specific number directly, you must add the android. permission. CALL_PHONE permission to the application.

Open the dialing application only:

Intent intent = newIntent (android. content. Intent. ACTION_DIAL );

3. Map

Intent intent = newIntent (android. content. Intent. ACTION_VIEW, Uri.

Parse ("geo: 37.0,-122.0 "));

4. display the contact list

Intent intent = newIntent (android. content. Intent. ACTION_VIEW, Uri.

Parse ("content: // contacts "));

5. Select a contact

Intent intent = newIntent (android. content. Intent. ACTION_PICK, Uri.

Parse ("content: // contacts "));

The constant android. content. Intent. ACTION_VIEW actually refers to the action "android. intent. action. VIEW", so you can write it like this, for example, select a contact:

Intent intent = new Intent ("android. intent. action. VIEW", Uri.

Parse ("content: // contacts "));

You can also write as follows:

Intent intent = new Intent ("android. intent. action. VIEW ");

Intent. setData (Uri. parse ("content: // contacts "));

5. Start Activity

1. General Method

Intent intent = new Intent (this, OtherActivity. class );

StartActivity (intent );

2. Start with action

Set action when declaring Activity in manifest. xml

Android: label = "OtherActivity"

Android: name = "com. example. OtherActivity"

>

// It is best to use the package path for action

.

Start Activity

Intent intent = new Intent ("raleweigh. OtherActivity ");

StartActivity (intent );

Vi. GroupView view group

1. LinearLayout

2. AbsoluteLayout

3. TableLayout

4. RelativeLayout

5. FrameLayout

6. ScrollView

You can use the absolute layout AbsoluteLayout in combination with layout_x and layout_y to specify the position of the View control.

VII. Getting focus

1. If a widget obtains the focus, add the following two sentences to obtain the focus.

Android: focusable = "true"

Android: focusableInTouchMode = "true"

2. Enable EditText to automatically obtain the focus, but the virtual keyboard is not displayed.

You need to set stateHidden when declaring Activity in the manifest. xml file, as shown in

Android: name = ". MainActivity"

Android: windowSoftInputMode = "stateHidden"

>

8. Horizontal and vertical screen Switching

(1) Adaptive display direction

1. Anchoring

Adjust stretch screen with RelativeLayout

2. Resize and reposition

Use two layout-land layout and layout

(2) configuration changes are maintenance status information.

1. onPause ()-triggered when an Activity is terminated or transferred to the background

2. onSaveInstanceState ()-triggered when an Activity is to be terminated or transferred to the background

Unlike the Pause () method, when an Activity is detached from the stack (for example, when a user presses the Back button), onSaveInstanceState () is not triggered (), this is because it does not need to be restored later.

For example, save:

@ Override

Protected void onSaveInstanceState (BundleoutState ){

// Pay attention to the order of super

OutState. putString ("ID", "1234 ");

Super. onSaveInstanceState (outState );

}

OnRestoreInstanceState:

@ Override

Protected void onRestoreInstanceState (BundlesavedInstanceState ){

Super. onRestoreInstanceState (savedInstanceState );

StringID = savedInstanceState. getString ("ID ");

}

3. onRetainNonConfigurationInstance ()-triggered when an Activity is to be destroyed due to configuration changes (for example, switching between the screen and the keyboard.

When you need to temporarily save some data, such as downloading data from the Web service and changing the screen direction, you can use this method to save the data.

Save, you can return any object:

@ Override

Public ObjectonRetainNonConfigurationInstance (){

String result = "some text topreserve ";

Returnresult;

}

Read data:

@ Override

Protected void onCreate (BundlesavedInstanceState ){

Super. onCreate (savedInstanceState );

String str = (String) getLastNonConfigurationInstance ();

}

(3) Changing the inspection direction

@ Override

Protected void onCreate (BundlesavedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

WindowManagerwm = getWindowManager ();

// The getDefaultDisplay () method returns a Display object indicating the device screen.

Displayd = wm. getDefaultDisplay ();

If (d. getWidth ()> d. getHeight ()){

// Landscape mode

} Else {

// Portraitmode

}

}

(4) control the Activity direction and set the screen direction

1. Set the code in the onCreate () method:

Horizontal

SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE );

Vertical

SetRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );

3. Set in manifest. xml (portrait of portrait, landscape of landscape)

Android: name = "com. example. test. MainActivity"

Android: label = "@ string/app_name"

Android: screenOrientation = "portrait">

9. Action Bar (Android 3.0 or above supported)

(1) Open or hide the ActionBar

1. hide the ActionBar. You can set it in manifest. xml, and set actionBar. hide () in the code ();

Android: label = "@ string/app_name"

Android: name = ". MyActionBarActivity"

Android: theme = "@ android: style/Theme. Holo. NoActionBar"

/>

2. Open ActionBar and set the code

@ Override

Protected void onCreate (BundlesavedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

ActionBar actionBar = getActionBar ();

// Hide actionBar. hide ();

ActionBar. show (); // open

}

Note: android: theme in manifest. xml cannot be set. Otherwise, null is reported.

(2) customize action items and application icons

1. Customize action items

MenuItem. setShowAsAction (MenuItem. SHOW_AS_ACTION_IF_ROOM );

Note:

A) MenuItem. SHOW_AS_ACTION_IF_ROOM if there is space on the Action Bar, this menu item is displayed as an Action item, and the displayed menu item has no text.

B) (MenuItem. SHOW_AS_ACTION_IF_ROOM | MenuItem. SHOW_AS_ACTION_WITH_TEXT) the action item displays icons and text at the same time.

2. To enable the application icon to be clicked on the ActionBar, call the setDisplayHomeAsUpEnabled () method:

@ Override

Protected void onCreate (BundlesavedInstanceState ){

Super. onCreate (savedInstanceState );

SetContentView (R. layout. main );

ActionBar actionBar = getActionBar ();

// ActionBar. hide ();

ActionBar. show (); // display Action Bar

// Call the setDisplayHomeAsUpEnabled () method to enable the application icon to be clicked.

ActionBar. setDisplayHomeAsUpEnabled (true );

}

Listener:

@ Override

Public boolean onOptionsItemSelected (MenuItemitem ){

Switch (item. getItemId ()){

Case android. R. id. home:

Toast. makeText (this, "Youclicked on the Application icon", Toast. LENGTH_SHORT). show ();

Break;

}

Return true;

}


(3)

10. Intent Flag

1. Intent. FLAG_ACTIVITY_CLEAR_TOP: make sure that a series of activities in the Backstack are cleared when you click the application icon in the Action Bar. If you click the Back button, other activities in the application will not be displayed again.

11. Menu

1. Set the shortcut key for a menu item:

Menu. setQwertyMode (true );

MenuItem. setAlphabeticShortcut ()

2. Bind a View to the context menu: view. setOnCreateContextMenuListener (this );

12. In the Time View, the system time is displayed and cannot be changed.

1. AnalogClock has sub-needles and hour hands

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

/>


2. DigitalClock digital display time

Android: layout_width = "wrap_content"

Android: layout_height = "wrap_content"

/>

XIII. WebView

1. To avoid page redirection, you must implement the WebViewClient class and override the shouldOverrideUrlLoading () method.

Class Callback extends WebViewClient {

@ Override

Public boolean shouldOverrideUrlLoading (WebView view, Stringurl ){

Return (false );

}

}

Webview. setWebViewClient (new Callback ());

2. Create an HTML string, loadDataWithBaseURL ()

String mimeType = "text/html ";

String encoding = "UTF-8 ";

String html = "A simple HTMLpage

Lazy dog

"

WebView. loadDataWithBaseURL ("", html, mimeType, encoding ,"");

14. Content Provider

1. query strings

A) content: // media/internal/images returns a list of internal images returned one by one stored on the device

B) content: // media/external/images returns a list Of all images stored in the external memory of the device (such as the SD card ).

C) content: // call_log/CILS returns a list of all calls recorded in CallLog.

D) content: // brower/bookmarks returns a list of bookmarks stored in the browser.

2. Check the version of the currently running application

Android. OS. Build. VERSION. SDK_INT --- value range (3-19)

3. predefined query string constants

Contacts. CONTENT_URI

Browser. BOOKMARKS_URI

Browser. SEARCHES_URI

CallLog. CONTENT_URI

MediaStore. image. Media. INTERNAL_CONTENT_URI

MediaStore. image. Media. EXTERNAL_CONTENT_URI

Settings. CONTENT_URI

4. Others

1) query contacts

UriallContacts = Uri. parse ("content: // contacts/people ");

Or:

Uri allContacts = ContactsContract. Contacts. CONTENT_URI;

Note: For Android2.0 or later, you must use Contacts. CONTENT_URI to query basic Contacts records.

2) retrieve the first contact

Uri allContacts = Uri. parse ("content: // contacts/people/1 ");

Or

Uri allContacts = ContactsUris. widthAppendedId

(ContactsContract. Contacts. CONTENT_URI, 1 );

3) traverse contacts

Private void printContacts (Cursor c ){

If (c. moveToFirst ()){

Do {

StringcontactId = c. getString (c. getColumnIndex (ContactsContract. Contacts. _ ID ));

StringcontactDisplayName = c. getString (c. getColumnIndex (ContactsContract. Contacts. DISPLAY_NAME ));

Log. v ("ContentProviders", contactId + "," + contactDisplayName );

// To access a contact's number

// Query the URI in ContactsContract. ConmmonDataKinds. Phone. CONTENT_URI

InthasPhone = c. getInt (c. getColumnIndex (ContactsContract. Contacts. HAS_PHONE_NUMBER ));

If (hasPhone = 1 ){

Cursor phoneCursor = getContentResolver (). query (ContactsContract. CommonDataKinds. Phone. CONTENT_URI, null,

ContactsContract. CommonDataKinds. Phone. CONTACT_ID + "=" + contactId, null, null );

While (phoneCursor. moveToNext ()){

Log. v ("Content Providersphone =", phoneCursor. getString (phoneCursor. getColumnIndex (ContactsContract. CommonDataKinds. Phone. NUMBER )));

}

PhoneCursor. close ();

}

} While (c. moveToNext ());

}

}

5. retrieve a managed cursor

ManagedQuery (uri, projection, selection, selectionArgs, sortOrder );

A) uri

For example, Uri allContacts = ContactsContract. Contacts. CONTENT_URI;

B) Projection

For example, String [] projection = new String [] {

ContactsContract. Contacts. _ ID,

ContactsContract. Contacts. DISPLAY_NAME,

ContactsContract. Contacts. HAS_PHONE_NUMBER

};

C) Screening

String selection = ContactsContract. Contacts. DISPLAY_NAME + "LIKE '% Lin '";

Filtering conditions, both before and after use

String selection = ContactsContract. Contacts. DISPLAY_NAME + "LIKE? ";

String [] selectionArgs = newString {"% Lin "};

D) sorting

String sortOrder = ContactsContract. Contacts. DISPLAY_NAME + "ASC

15. SMS

1. Send messages

SmsManager sms = SmsManager. getDefault ();

Sms. sendTextMessage (destinationAddress, scAddress, text, sentIntent, deliveryIntent );

Note:

A) destinationAddress-recipient's phone number

B) scAddress-service center address. null indicates the default SMSC.

C) text-SMS message content

D) sentIntent-the suspended Intent called after the message is sent. It can be null.

E) deliveryIntent-the pending Intent called after message delivery, which can be null

Note: If you use the SmsManager class to send SMS messages programmatically, the messages sent will not appear in the sender's built-in Messaging application.

16. Common shortcut keys

1. Ctrl + Shift + O import all the packages required for this class

2. Alt +/opening prompt

3. Ctrl + Shift + Enter

4. Shift + Enter

5. Ctrl + Shift + G search for the code lines that call a method/Object/class

6. Ctrl + Shift + R search for resources (you need to double-click the resource name, for example, search for layout)

7. Shift + Alt + R rename, method name/Object Name/class name/Resource Name

8. Ctrl +/comment out a row

9. Shif + Alt + J write annotation for a method

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.