Android. ProgressDialog example

    private DialogFragment mDialog;
...
            mDialog = ProgressDialogFragment.newInstance();
            mDialog.show(getFragmentManager(), "Shutdown");
...
    public static class ProgressDialogFragment extends DialogFragment {

        public static ProgressDialogFragment newInstance() {
            return new ProgressDialogFragment();
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final ProgressDialog dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Activity Shutting Down.");
            dialog.setIndeterminate(true);
            return dialog;
        }
    }

Android. ActionBar Tabs example

public class TabLayoutActivity extends Activity {

    private static final String ANIMALS_TABSTRING = "Animals";
    private static final String FLOWERS_TABSTRING = "Flowers";
    protected static final String THUMBNAIL_IDS = "thumbNailIDs";

    private ArrayList<Integer> mThumbIdsFlowers = new ArrayList<Integer>(
            Arrays.asList(R.drawable.image1, R.drawable.image2,
                    R.drawable.image3, R.drawable.image4, R.drawable.image5,
                    R.drawable.image6, R.drawable.image7, R.drawable.image8,
                    R.drawable.image9, R.drawable.image10, R.drawable.image11,
                    R.drawable.image12));

    private ArrayList<Integer> mThumbIdsAnimals = new ArrayList<Integer>(
            Arrays.asList(R.drawable.sample_1, R.drawable.sample_2,
                    R.drawable.sample_3, R.drawable.sample_4,
                    R.drawable.sample_5, R.drawable.sample_6,
                    R.drawable.sample_7, R.drawable.sample_0));

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        final ActionBar tabBar = getActionBar();
        tabBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        GridFragment flowerFrag = new GridFragment();
        Bundle args = new Bundle();
        args.putIntegerArrayList(THUMBNAIL_IDS, mThumbIdsFlowers);
        flowerFrag.setArguments(args);
        tabBar.addTab(tabBar.newTab().setText(FLOWERS_TABSTRING)
                .setTabListener(new TabListener(flowerFrag)));

        GridFragment animalFrag = new GridFragment();
        args = new Bundle();
        args.putIntegerArrayList(THUMBNAIL_IDS, mThumbIdsAnimals);
        animalFrag.setArguments(args);
        tabBar.addTab(tabBar.newTab().setText(ANIMALS_TABSTRING)
                .setTabListener(new TabListener(animalFrag)));

    }

    public static class TabListener implements ActionBar.TabListener {
        private final Fragment mFragment;

        public TabListener(Fragment fragment) {
            mFragment = fragment;
        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (null != mFragment) {
                ft.replace(R.id.fragment_container, mFragment);
            }
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (null != mFragment)
                ft.remove(mFragment);
        }
    }
}

Android. TimePicker example

package course.examples.UI.timepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class TimePickerActivity extends Activity {

    private TextView mTimeDisplay;
    private Button mPickTime;

    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;

    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            updateDisplay();
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date
        updateDisplay();
    }

    // updates the time we display in the TextView
    private void updateDisplay() {
        mTimeDisplay.setText(new StringBuilder().append(pad(mHour)).append(":")
                .append(pad(mMinute)));
    }

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
                    false);
        }
        return null;
    }

}

Android. DatePicker example

package course.examples.UI.datepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DatePickerActivity extends Activity {

    private TextView mDateDisplay;
    private Button mPickDate;
    private int mYear;
    private int mMonth;
    private int mDay;

    static final int DATE_DIALOG_ID = 0;

      // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // capture our View elements
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        mPickDate = (Button) findViewById(R.id.pickDate);

        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();
    }
   
     // updates the date in the TextView
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }
   
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
}

Android. Auto complete TextView with ArrayAdapter

        // Create an ArrayAdapter containing country names
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.list_item, COUNTRIES);

        // Set the adapter for the AutoCompleteTextView
        textView.setAdapter(adapter);

Android. Working with fragments

Add new fragment

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(R.id.fragment_container, mFriendsFragment);
            transaction.commit();

Replace existing fragment with its state

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.fragment_container, mFeedFragment);
            transaction.addToBackStack(null);
            transaction.commit();

Start another app using its permission

Application 1:

    private static final String DANGEROUS_ACTIVITY_ACTION = "course.labs.permissions.DANGEROUS_ACTIVITY";
...
        startActivity(new Intent(DANGEROUS_ACTIVITY_ACTION));

Application 1 AndroidManifest.xml:

    <uses-permission android:name="course.labs.permissions.DANGEROUS_ACTIVITY_PERM" />

Application 2 AndroidManifest.xml:

    <permission
       android:name="course.labs.permissions.DANGEROUS_ACTIVITY_PERM"
       android:protectionLevel="dangerous" >
    </permission>
...
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="course.labs.permissions.DANGEROUS_ACTIVITY" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

Android. Intent chooser example

This example is to show intent chooser.
Application A:

        Intent baseIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
       
        // TODO - Create a chooser intent, for choosing which Activity
        // will carry out the baseIntent
        // (HINT: Use the Intent class' createChooser() method)
        Intent chooserIntent = Intent.createChooser(baseIntent, CHOOSER_TEXT);
       
        // TODO - Start the chooser Activity, using the chooser intent
        startActivity(chooserIntent);

Application B AndroidManifest.xml:

            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <data android:scheme="http"/>
            </intent-filter>

Android. startActivityForResult example

Activity A:

static private final int GET_TEXT_REQUEST_CODE = 1;
...
        // TODO - Create a new intent to launch the ExplicitlyLoadedActivity class
        Intent explicitIntent = new Intent(getApplicationContext(), ExplicitlyLoadedActivity.class);
       
        // TODO - Start an Activity using that intent and the request code defined above
        startActivityForResult(explicitIntent, GET_TEXT_REQUEST_CODE);
...
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
        Log.i(TAG, "Entered onActivityResult()");
       
        // TODO - Process the result only if this method received both a
        // RESULT_OK result code and a recognized request code
        // If so, update the Textview showing the user-entered text.
        if(requestCode == GET_TEXT_REQUEST_CODE && resultCode==RESULT_OK){
            String input = data.getStringExtra("result");
            mUserTextView.setText(input);
        }
    }

Activity B:

        // TODO - Create a new intent and save the input from the EditText field as an extra
        Intent returnIntent = new Intent();
        returnIntent.putExtra("result", input);
       
        // TODO - Set Activity's result with result code RESULT_OK
        setResult(RESULT_OK, returnIntent);
       
        // TODO - Finish the Activity
        finish();

Expandable GridView inside ScrollView

ExpandedGridView:

package com.globalsolutions.medapp.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;

public class ExpandedGridView extends GridView {

    boolean expanded = false;

    public ExpandedGridView(Context context) {
        super(context);
    }

    public ExpandedGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExpandedGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public boolean isExpanded() {
        return expanded;
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // HACK! TAKE THAT ANDROID!
        if (isExpanded()) {
            // Calculate entire height by providing a very large height hint.
            // But do not use the highest 2 bits of this integer; those are
            // reserved for the MeasureSpec mode.
            int expandSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);

            ViewGroup.LayoutParams params = getLayoutParams();
            params.height = getMeasuredHeight();
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void setExpanded(boolean expanded) {
        this.expanded = expanded;
    }
}

XML:

                <com.globalsolutions.medapp.ui.ExpandedGridView
                   android:id="@+id/gvTypes"
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:numColumns="2" >
                </com.globalsolutions.medapp.ui.ExpandedGridView>

Activity or Fragment:

ExpandedGridView gvTypes = (ExpandedGridView) rootView.findViewById(R.id.gvTypes);
....
gvTypes.setAdapter(typesListAdapter);
gvTypes.setExpanded(true);