Basic Programming
Dialogs
by Eakapong Kattiya
Monday, July 15, 13
by Eakapong Kattiya
Toasts
- Small popup
- Automatically disappear
- Timeout :TOAST_LONG / TOAST_SHORT
Toast.makeText(getApplicationContext(),
	 "Message saved as draft,
	 	 	 	 	 Toast.LENGTH_LONG).show();
Monday, July 15, 13
by Eakapong Kattiya
Alerts
Alerts without title bar
Alerts with title bar
Monday, July 15, 13
by Eakapong Kattiya
Basic Buttons
Buttons
Borderless Buttons
Buttons
Monday, July 15, 13
public void showAlert(){
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, android.R.style.Theme_Holo);
	
AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);
	 builder.setMessage("Unfortunately,the process com.android.phone has stopped");
	 builder.setPositiveButton("OK",null);
	 builder.setNegativeButton("Report", new DialogInterface.OnClickListener() {
	 @Override
	 public void onClick(DialogInterface dialog, int which) {
	 	 //show Report Activity
	 }
	 });
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog :Alerts without title bar
Monday, July 15, 13
public void showAlertWithTitleBar(){
ContextThemeWrapper wrapper = new ContextThemeWrapper(this, android.R.style.Theme_Holo);
	
AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle("Erase USB Storage ?");
	 builder.setMessage("You’ll lose all photos and media!");
	 builder.setPositiveButton("Erase", new DialogInterface.OnClickListener() {
	 @Override
	 public void onClick(DialogInterface dialog, int which) {
	 	 //do Report Activity
	 }
	 });
	 builder.setNegativeButton("Cancel", null);
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog :Alerts with title bar
Monday, July 15, 13
by Eakapong Kattiya
Dialogs
1. Optional Title
2. Content area
3.Action button
Monday, July 15, 13
by Eakapong Kattiya
Text Fields : EditText
Single line &
Multi line
Text field types
Text selection
Monday, July 15, 13
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_layer);
builder.setTitle("Prompt user input");
	 	
builder.setMessage("Please type a message.");
// Set an EditText view to get user input
final EditText input = new EditText(this);
builder.setView(input);
	 	
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
	 @Override
	 public void onClick(DialogInterface dialog, int which) {
	 	 Log.i("AlertDialog","input text =" + input.getText().toString());
	 }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	 @Override
	 public void onClick(DialogInterface dialog, int which) {
	 }
});
builder.create().show();
}
by Eakapong Kattiya
AlertDialog : Prompt user input
Monday, July 15, 13
by Eakapong Kattiya
Switches
Radio Buttons
On/Off Switches
Checkboxes
Monday, July 15, 13
String[] items = {"Notification", "Music", "Location"};
boolean[] itemsChecked = new boolean[items.length];
AlertDialog.Builder builder = new AlertDialog.Builder(this);
	 builder.setIcon(R.drawable.ic_layer);
	 builder.setTitle("Multi Choice Items");
	 builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
	 	 }
	 });
	 builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
	 public void onClick(DialogInterface dialog, int which) {
	 }
	 });
	 builder.setSingleChoiceItems(items,-1,
new DialogInterface.OnClickListener() {
	 @Override
	 public void onClick(DialogInterface dialog, int item) {
	 	 }
	 });
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog : Single choice dialog
Monday, July 15, 13
String[] items = {"Notification", "Music", "Location"};
boolean[] itemsChecked = new boolean[items.length];
AlertDialog.Builder builder = new AlertDialog.Builder(this);
	 builder.setIcon(R.drawable.ic_layer);
	 builder.setTitle("Multi Choices Dialog");
	 builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
	 	 }
	 });
	 builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
	 public void onClick(DialogInterface dialog, int which) {
	 }
	 });
	 builder.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
	 	 public void onClick(DialogInterface dialog, int which, boolean isChecked) {
	 	 }
	 });
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog : Multi choices dialog
Monday, July 15, 13
by Eakapong Kattiya
Index Scrolling
Scroll Indicator
Scrolls
Monday, July 15, 13
by Eakapong Kattiya
Pickers
Space considerations
Date & Time pickers
Monday, July 15, 13
by Eakapong Kattiya
SharedPreferences : Sample
//Create Preferences
	 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	 //Create Preference Editor
	 SharedPreferences.Editor prefEditor = prefs.edit();
	 prefEditor.putBoolean(“key1”, true);
	 prefEditor.putString(“key2”, “value1”);
prefEditor.putString(“key3”, “value2”);
	 //Save Preferences with Editor
	 prefEditor.commit();
	 //Load Preferences
	 prefs.getBoolean(“key1”,false);
	 prefs.getString(“key2”);
Monday, July 15, 13
by Eakapong Kattiya
SharedPreferences : SecondActivity.java
String[] items = {"Notification", "Music", "Location"};
boolean[] itemsChecked = new boolean[items.length];
public void loadFromPreference(){
	 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	
for (int i = 0; i < items.length; i++) {
	 	 boolean isChecked = prefs.getBoolean(items[i],false);
	 	 itemsChecked[i] = isChecked ;
	 }
}
Monday, July 15, 13
@Override
	 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	 	 // TODO Auto-generated method stub
	 	 Item item = (Item) arg0.getItemAtPosition(arg2);
	 	 Log.i("Click listView", item.title);
	 	 if(arg2 == 0){
	 	 	 showPopupMenu();
	 	 }else if(arg2 == 1){
	 	 	 showPopupMenuWithIcon();
	 	 }else if(arg2 == 2){
	 	 	 showAlert();
	 	 }else if(arg2 == 3){
	 	 	 showAlertWithTitleBar();
	 	 }else if(arg2 == 4){
	 	 	 showPromptUserInputDialog();
	 	 }else if(arg2 == 5){
	 	 	 showSingleChoiceDialog();
	 	 }else if(arg2 == 6){
	 	 	 showMultiChoiceDialog();
	 	 }else if(arg2 == 7){
	 	 	 showMultiChoiceDialogWithPref();
	 	 }
	 }
by Eakapong Kattiya
AlertDialog with Preferences : SecondActivity.java
Monday, July 15, 13
public void showMultiChoiceDialogWithPref() {
loadFromPreference();
	 AlertDialog.Builder builder = new AlertDialog.Builder(this);
	 builder.setIcon(R.drawable.ic_layer);
	 builder.setTitle("Setting");
	 builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
	 	 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
	 	 SharedPreferences.Editor prefEditor = prefs.edit();
	 	 for (int i = 0; i < items.length; i++) {
	 	 	 String message = items[i] + " checked!";
	 	 	 Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
	 	 	 prefEditor.putBoolean(items[i], itemsChecked[i]);
	 	 }
	 	 prefEditor.commit();
	 }
	 });
	 builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
	 public void onClick(DialogInterface dialog, int which) {
	 }
	 });
	 builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
	 	 public void onClick(DialogInterface dialog, int which, boolean isChecked) {
	 	 	 itemsChecked[which] = isChecked ;
	 	 }
	 });
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog with Preferences : SecondActivity.java
Monday, July 15, 13
by Eakapong Kattiya
Popups (>API 11)
Monday, July 15, 13
by Eakapong Kattiya
Spinners
Spinners in forms
Spinners in action bars
(>API 11)
Monday, July 15, 13
public void showPopupMenuWithIcon(){
	 final String [] items = new String[] {"From Gallery", "From Camera"};
	 final Integer[] icons = new Integer[] {android.R.drawable.ic_menu_gallery,
android.R.drawable.ic_menu_camera};
	
ListAdapter adapter = new ArrayAdapterWithIcon(this, items, icons);
	 ContextThemeWrapper wrapper = new ContextThemeWrapper(this,
android.R.style.Theme_Holo_Light_Dialog);
	
AlertDialog.Builder builder = new AlertDialog.Builder(wrapper);
	 builder.setIcon(android.R.drawable.ic_menu_share);
	 builder.setTitle("Share Photo");
	 builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
	 public void onClick(DialogInterface dialog, int item) {
	 	 	 	 //...
	 	 }
	 });
	 builder.create().show();
}
by Eakapong Kattiya
AlertDialog : Popup Menu With Icon
Monday, July 15, 13
public class ArrayAdapterWithIcon extends ArrayAdapter<String> {
	 private List<Integer> images;
	 public ArrayAdapterWithIcon(Context context, List<String> items, List<Integer> images) {
	 	 super(context, android.R.layout.select_dialog_item, items);
	 	 this.images = images;
	 }
	 public ArrayAdapterWithIcon(Context context, String[] items, Integer[] images) {
	 	 super(context, android.R.layout.select_dialog_item, items);
	 	 this.images = Arrays.asList(images);
	 }
	 @Override
	 public View getView(int position, View convertView, ViewGroup parent) {
	 	 View view = super.getView(position, convertView, parent);
	 	 TextView textView = (TextView) view.findViewById(android.R.id.text1);
	 	 textView.setCompoundDrawablesWithIntrinsicBounds(images.get(position), 0, 0, 0);
	 	 textView.setCompoundDrawablePadding(
	 	 	 	 (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12,
getContext().getResources().getDisplayMetrics()));
	 	 return view;
	 }
}
by Eakapong Kattiya
ArrayAdapterWithIcon.java
Monday, July 15, 13
by Eakapong Kattiya
Gestures
Touch Long press Swipe
Drag Double touch Pinch open Pinch close
Monday, July 15, 13
class MyGestureListener extends GestureDetector.SimpleOnGestureListener{
	 @Override
	 public boolean onSingleTapUp(MotionEvent ev) {
	 	 Log.d("onSingleTapUp",ev.toString());
	 	 return true;
	 }
	 public boolean onDoubleTap(MotionEvent ev) {
	 	 Log.d("onDoubleTap",ev.toString());
	 	 return true;
	 }
	 @Override
	 public void onShowPress(MotionEvent ev) {
	 	 Log.d("onShowPress",ev.toString());
	 }
	 @Override
	 public void onLongPress(MotionEvent ev) {
	 	 Log.d("onLongPress",ev.toString());
	 }
	 @Override
	 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
	 	 Log.d("onScroll",e1.toString());
	 	 return true;
	 }
	 @Override
	 public boolean onDown(MotionEvent ev) {
	 	 Log.d("onDownd",ev.toString());
	 	 return true;
	 }
	 @Override
	 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	 	 Log.d("d",e1.toString());
	 	 Log.d("e2",e2.toString());
	 	 return true;
	 }
}
by Eakapong Kattiya
Gestures : create MyGestureListener.java
Monday, July 15, 13
public class MainActivity extends TabActivity {
	 GestureDetector mGestureDetector ;
	 @Override
	 protected void onCreate(Bundle savedInstanceState) {
	 	 super.onCreate(savedInstanceState);
	 	 setContentView(R.layout.activity_main);
//..
	 	
	 	 mGestureDetector = new GestureDetector(this, new MyGestureListener());
	 }
	 @Override
	 public boolean onTouchEvent(MotionEvent event) {
	 if (mGestureDetector.onTouchEvent(event))
	 return true;
	 else
	 return false;
	 }
by Eakapong Kattiya
Gestures : MainActivity.java
Monday, July 15, 13
public class MyShakeListener implements SensorEventListener {
	 private String TAG = MyShakeListener.class.getSimpleName();
	 private static final int FORCE_THRESHOLD = 800;
	 private static final int TIME_THRESHOLD = 100;
	 private static final int SHAKE_TIMEOUT = 500;
	 private static final int SHAKE_DURATION = 1000;
	 private static final int SHAKE_COUNT = 5;
	 private SensorManager mSensorMgr;
	 private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
	 private long mLastTime;
	 private OnShakeListener mShakeListener;
	 private Context mContext;
	 private int mShakeCount = 0;
	 private long mLastShake;
	 private long mLastForce;
	 public interface OnShakeListener {
	 	 public void onShake();
	 }
	 public MyShakeListener(Context context) {
	 	 Log.d(TAG,"ShakeListener invoked---->");
	 	 mContext = context;
	 	 resume();
	 }
	 public void setOnShakeListener(OnShakeListener listener) {
	 	 Log.d(TAG,"ShakeListener setOnShakeListener invoked---->");
	 	 mShakeListener = listener;
	 }
by Eakapong Kattiya
Shake : MyShakeListener.java (1)
Monday, July 15, 13
public void resume() {
	 	 mSensorMgr = (SensorManager) mContext
	 	 	 	 .getSystemService(Context.SENSOR_SERVICE);
	 	 if (mSensorMgr == null) {
	 	 	 throw new UnsupportedOperationException("Sensors not supported");
	 	 }
	 	 boolean supported = false;
	 	 try {
	 	 	 supported = mSensorMgr.registerListener(this,
	 	 	 	 	 mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
	 	 	 	 	 SensorManager.SENSOR_DELAY_GAME);
	 	 } catch (Exception e) {
	 	 	 Toast.makeText(mContext, "Shaking not supported", Toast.LENGTH_LONG)
	 	 	 .show();
	 	 }
	 	 if ((!supported) && (mSensorMgr != null))
	 	 	 mSensorMgr.unregisterListener(this);
	 }
	 public void pause() {
	 	 if (mSensorMgr != null) {
	 	 	 mSensorMgr.unregisterListener(this);
	 	 	 mSensorMgr = null;
	 	 }
	 }
by Eakapong Kattiya
Shake : MyShakeListener.java (2)
Monday, July 15, 13
@Override
	 public void onSensorChanged(SensorEvent event) {
	 	 if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
	 	 	 return;
	 	 long now = System.currentTimeMillis();
	 	 if ((now - mLastForce) > SHAKE_TIMEOUT) {
	 	 	 mShakeCount = 0;
	 	 }
	 	 if ((now - mLastTime) > TIME_THRESHOLD) {
	 	 	 long diff = now - mLastTime;
	 	 	 float speed = Math.abs(event.values[SensorManager.DATA_X]
	 	 	 	 	 + event.values[SensorManager.DATA_Y]
	 	 	 	 	 	 	 + event.values[SensorManager.DATA_Z] - mLastX - mLastY
	 	 	 	 	 	 	 - mLastZ)
	 	 	 	 	 	 	 / diff * 10000;
	 	 	 if (speed > FORCE_THRESHOLD) {
	 	 	 	 if ((++mShakeCount >= SHAKE_COUNT)
	 	 	 	 	 	 && (now - mLastShake > SHAKE_DURATION)) {
	 	 	 	 	 mLastShake = now;
	 	 	 	 	 mShakeCount = 0;
	 	 	 	 	 Log.d(TAG,"ShakeListener mShakeListener---->"+mShakeListener);
	 	 	 	 	 if (mShakeListener != null) {
	 	 	 	 	 	 mShakeListener.onShake();
	 	 	 	 	 }
	 	 	 	 }
	 	 	 	 mLastForce = now;
	 	 	 }
	 	 	 mLastTime = now;
	 	 	 mLastX = event.values[SensorManager.DATA_X];
	 	 	 mLastY = event.values[SensorManager.DATA_Y];
	 	 	 mLastZ = event.values[SensorManager.DATA_Z];
	 	 }
	 }
by Eakapong Kattiya
Shake : MyShakeListener.java (3)
Monday, July 15, 13
public void addShakeListener(){
	 	 MyShakeListener mShaker = new MyShakeListener(this);
	 	 mShaker.setOnShakeListener(new MyShakeListener.OnShakeListener () {
	 	 	 public void onShake()
	 	 	 {
	 	 	 	 Toast.makeText(getApplicationContext(),
	 	 	 	 	 	 "You have shaken your phone", Toast.LENGTH_SHORT).show();
	 	 	 	 MediaPlayer mediaPlayer ;
	 	 	 	 mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.background);
	 	 	 	 mediaPlayer.start();
	 	 	 }
	 	 });
	 }
by Eakapong Kattiya
Gestures : MainActivity.java
Monday, July 15, 13
Multimedia
by Eakapong Kattiya
Monday, July 15, 13
by Eakapong Kattiya
Camera & Gallery
//Take a photo with camera
Intent intentCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(intentCamera, "Take a with:"),MY_CAMERA_REQUEST);
	
//Choose photo from gallery
Intent intentGallery = new Intent(android.content.Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intentGallery,MY_CAMERA_REQUEST);
//Get Taken Photo from camera & gallery
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	 if (requestCode == MY_CAMERA_REQUEST && resultCode == RESULT_OK) {
	 	 Bitmap photo = (Bitmap) data.getExtras().get("data");
	 	 	
	 	 ImageView imageView = (ImageView)findViewById(R.id.imageView1);
	 	 imageView.setImageBitmap(photo);
	 }
}
Monday, July 15, 13
by Eakapong Kattiya
MediaPlayer : Play Raw Music File (background.mp3)
//Start Music
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.background);
mediaPlayer.start();
//Set Volume
AudioManager mAudioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
int current_volume =mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mediaPlayer.setVolume(current_volume, current_volume);
//Set Completion Listener
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
	 }
});
Monday, July 15, 13
by Eakapong Kattiya
VideoView : Offline & Streaming : activity_about.xml
<VideoView
android:id="@+id/videoView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
Monday, July 15, 13
by Eakapong Kattiya
VideoView : Offline & Streaming :VideoViewActivity.java
String streamingURL = "http://58.64.30.205/PaidContent/
ZGEwZDZiZWRmZDdjZTM2M2M0ZTA3ZjU1OWI4ZWY4M2YKLIVE2.m3u8" ;
String streamingTest = "http://devimages.apple.com/iphone/
samples/bipbop/gear1/prog_index.m3u8";
String offlineURL = "android.resource://" + getPackageName() + "/" +
R.raw.swipe_tabs ;
VideoView videoView = (VideoView)findViewById(R.id.videoView1);
	 videoView.setVideoURI(Uri.parse(streamingURL));
	 videoView.setMediaController(new MediaController(this));	
	 videoView.requestFocus();
	 videoView.setKeepScreenOn(true);
	 videoView.start();
VideoPlayer is a wrapper for MediaPlayer
VideoPlayer is easier than MediaPlayer
Monday, July 15, 13
by Eakapong Kattiya
Seek Bars
Monday, July 15, 13