Tự học Begin Android 4 - Trial version

Embed Size (px)

Citation preview

  • 7/31/2019 T hc Begin Android 4 - Trial version

    1/16

  • 7/31/2019 T hc Begin Android 4 - Trial version

    2/16

    android:theme="@style/AppTheme">

    The Activity base class defines a series of events that govern the life cycle

    of an activity. The Activity class defines the following events:onCreate() Called when the activity is first createdonStart() Called when the activity becomes visible to the useronResume() Called when the activity starts interacting with the useronPause() Called when the current activity is being paused and the previous

    activity is being resumedonStop() Called when the activity is no longer visible to the useronDestroy() Called before the activity is destroyed by the system (either manually

    or by the system to conserve memory)onRestart() Called when the activity has been stopped and is restarting again

  • 7/31/2019 T hc Begin Android 4 - Trial version

    3/16

    By default,

    the activity

    created for

    you contains

    the

    onCreate()

    event. Within

    this event

    handler is the

    code that

    helps to

    display the

    UI elements

    of your

    screen.

    Understanding the Life Cycle of an Activity by adding the following statements in bold in

    the Activity101Activity.javafile:publicclass Activity101Activity extends Activity {

    String tag = "Lifecycle";

    /** Called when the activity is first created. */@Overridepublicvoid onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);// This activity load its UI using main.xml defined in res/layoutsetContentView(R.layout.main);Log.d(tag, "In the onCreate() event");

  • 7/31/2019 T hc Begin Android 4 - Trial version

    4/16

  • 7/31/2019 T hc Begin Android 4 - Trial version

    5/16

    Click the Backbutton ( ) on the Android Emulator, the following is printed

    (below figure):

    Click the Home button ( ) and hold it there. Click the Activities icon and observe

    the following:

    Click the Phone button ( ) on the Android emulator so that the activity is pushed

    to the background. Observe the output in the LogCat window:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    6/16

    Notice that the onDestroy()event is not called, indicating that the activity is still in

    memory. Exit the phone dialer by clicking the Back button. The activity is now visible

    again. Observe the output in the LogCat window:

    Applying Styles and Themes to an ActivityBy default, an activity occupies the entire screen. However, you can apply a dialog theme

    to an activity so that it is displayed as a floating dialog. To apply a dialog theme to anactivity, simply modify the element in the AndroidManifest.xmlfile by

    adding the android:themeattribute:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    7/16

    Hiding the Activity Title

    I can also hide the title of an activity if desired (such as when you just want to display a

    status update to the user). To do so, use the requestWindowFeature()method and pass it

    the Window.FEATURE_NO_TITLEconstant, like this in Activity101Activity.javafile:publicvoid onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    // hides the title barrequestWindowFeature(Window.FEATURE_NO_TITLE);// This activity load its UI using main.xml defined in res/layoutsetContentView(R.layout.main);Log.d(tag, "In the onCreate() event");

    }This will hide the title bar, as shown in below figure:

    Displaying a Dialog Window

  • 7/31/2019 T hc Begin Android 4 - Trial version

    8/16

    There are times when you need to display a dialog window to get a confirmation from the

    user. In this case, you can override the onCreateDialog()protected method defined in the

    Activity base class to display a dialog window. The following shows us how (in the

    main.xml):

    This be shown in below figure

    We fix codes in the Activity101Activity.javafile:publicclass Activity101Activity extends Activity {

    CharSequence[] items = {"Google", "Apple", "Microsoft"};boolean[] itemsChecked = newboolean[items.length];

    /** Called when the activity is first created. */@Overridepublicvoid onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout.main);

    }

    // OnCreateDialog method is called when we call the showDialog method// by clicking on button which name is "Click to display a dialog"publicvoid onClick(View v) {

    showDialog(0);}

    // Display a dialog@Overrideprotected Dialog onCreateDialog(int id) {

    switch (id) {case 0:

    returnnew AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("This is a dialog with some simple text...").setPositiveButton("OK",

    new DialogInterface.OnClickListener() {

    publicvoid onClick(DialogInterfacedialog, int which) {

  • 7/31/2019 T hc Begin Android 4 - Trial version

    9/16

    // TODO Auto-generated method stubToast.makeText(getBaseContext(),

    "OK clicked", Toast.LENGTH_SHORT).show();}

    }).setNegativeButton("Cancel",

    newDialogInterface.OnClickListener() {

    publicvoid onClick(DialogInterfacedialog, int which) {

    // TODO Auto-generated method stubToast.makeText(getBaseContext(),

    "Cancel clicked", Toast.LENGTH_SHORT).show();}

    }).setMultiChoiceItems(items, itemsChecked,

    newDialogInterface.OnMultiChoiceClickListener() {

    publicvoidonClick(DialogInterface dialog, int which, boolean isChecked) {

    // TODO Auto-generatedmethod stub

    Toast.makeText(getBaseContext(), items[which] + (isChecked ? "checked!":" unchecked!"), Toast.LENGTH_SHORT).show();

    }}).create();

    }returnnull;

    }

    @Overridepublicboolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);returntrue;

    }}Or rewrite onCreateDialogmethod in the way:@Override

    protected Dialog onCreateDialog(int id) {switch(id) {case 0:

    returnnew AlertDialog.Builder(this)

    .setIcon(R.drawable.ic_launcher)

    .setTitle("This is a dialog with some simple text...")

    .setPositiveButton("OK",new DialogInterface.OnClickListener() {

    publicvoid onClick(DialogInterface dialog, intwhichButton)

    {Toast.makeText(getBaseContext(), "OK clicked!",

    Toast.LENGTH_SHORT).show();}

  • 7/31/2019 T hc Begin Android 4 - Trial version

    10/16

    }).setNegativeButton("Cancel",

    new DialogInterface.OnClickListener() {publicvoid onClick(DialogInterface dialog, int

    whichButton){

    Toast.makeText(getBaseContext(), "Cancelclicked!", Toast.LENGTH_SHORT).show();

    }}

    ).setMultiChoiceItems(items, itemsChecked,

    new DialogInterface.OnMultiChoiceClickListener() {publicvoid onClick(DialogInterface dialog,int which, boolean isChecked) {

    Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":"

    unchecked!"),Toast.LENGTH_SHORT).show();

    }}

    ).create();}returnnull;

    }Run app and click button, this is shown in:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    11/16

    If we clickOKbutton, this is shown in:

    Or if we clickCancel Button, this is shown in:

    Displaying a Process (Please Wait) DialogWe add the following statements in highlight to the main.xmlfile:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    12/16

    android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Click to display a dialog"android:onClick="onClick"/>

    and add the following statements in highlight in Activity101Activity.javafile:publicvoid onClick(View v) {

    showDialog(0);}

    publicvoid onClick2(View v) {

    /* to create a progress dialog, you created an instance of the* ProgressDialog class and called its show() method*/

    final ProgressDialog dialog = ProgressDialog.show(this, "Doingsomething", "Please wait...", true);

    /* To perform a long-running task in the background, you created aThread

    * using a Runnable block*/

    new Thread(new Runnable() {publicvoid run() {

    try {// Simulate doing lengthy

    (5 seconds)Thread.sleep(5000);

    // dismiss the dialogdialog.dismiss();

    } catch (InterruptedException e){

    e.printStackTrace();}

    }}).start();

    }When we click button name Click to display a progress dialog, we have a dialog

    appear with title is Doing something and content is Please wait. The circleanimation icon near Please wait will rotate until elapse 5 seconds and then, this

    dialog disappear, we back to main layout of application.

    Displaying a More Sophisticated Progress Dialog

  • 7/31/2019 T hc Begin Android 4 - Trial version

    13/16

    We add the following lines in highlight to the main.xml file:

    and add the following statements in highlight to the

    Activity101Activity.java file:

    CharSequence[] items = {"Google", "Apple", "Microsoft"};boolean[] itemsChecked = newboolean[items.length];

    ProgressDialog progressDialog;

    /** Called when the activity is first created. */@Overridepublicvoid onCreate(Bundle savedInstanceState) {...}

    publicvoid onClick(View v) {showDialog(0);

    }

    publicvoid onClick2(View v) {...}

    publicvoid onClick3(View v) {showDialog(1);progressDialog.setProgress(0);new Thread(new Runnable(){

    publicvoid run() {for (int i=1; i

  • 7/31/2019 T hc Begin Android 4 - Trial version

    14/16

    }Run app, click button name Click to display a

    detailed progress dialog which will appear

    dialog as below figure It will count from 1 to 15, with a delay of onesecond between each number and each number

    correspond to 6%. The

    incrementProgressBy() method increments the

    counter in the progress dialog. When the

    progress dialog reaches 100%, it is dismissed.

    Linking Activities using IntentsWhen your application has more than one activity, you often need to navigate from one to

    another. In Android, you navigate between activities through what is known as an intent.The first of all, we create a new class in Activity101Activity project. As shown in below

    figure:

    It appear the New Java Class dialog and we fill name of new class in Name textbox and

    clickFinish button, as shown in below figure (next page):Next, we add the following statements to AndroidManifest.xml:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    15/16

    android:label="Second Activity">

    We continue create secondactivity.xmlin res/layoutby copy main.xmlin same folder.

    Open secondactivity.xmlfile and add the following in highlight:

  • 7/31/2019 T hc Begin Android 4 - Trial version

    16/16

    Open SecondActivity.java file and add the following:publicclass SecondActivity extends Activity {

    @Overridepublicvoid onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.secondactivity);}

    }Note:If we create secondactivity.xmlfile in other way,R.layoutstatement in

    setContentView() method will not understand secondactivity value (when write

    R.layout.secondactivity, Eclipse program will give error in paragraph contain this

    statement.Finish, we modify Activity101Activity.javafile:@Override

    publicvoid onCreate(Bundle savedInstanceState) {...}

    publicvoid onClick(View v) {startActivity(new Intent("net.learn2develop.SecondActivity"));

    }Debug application (Ctrl + F11). We show in below figure: