SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
Jussi Pohjolainen
 

Tendances (20)

Embracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend PerfEmbracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend Perf
 
Introduction toandroid
Introduction toandroidIntroduction toandroid
Introduction toandroid
 
Material Design and Backwards Compatibility
Material Design and Backwards CompatibilityMaterial Design and Backwards Compatibility
Material Design and Backwards Compatibility
 
Android - Working with Fragments
Android - Working with FragmentsAndroid - Working with Fragments
Android - Working with Fragments
 
New text document
New text documentNew text document
New text document
 
droidparts
droidpartsdroidparts
droidparts
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
Simplified Android Development with Simple-Stack
Simplified Android Development with Simple-StackSimplified Android Development with Simple-Stack
Simplified Android Development with Simple-Stack
 
Advancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and GesturesAdvancing the UI — Part 1: Look, Motion, and Gestures
Advancing the UI — Part 1: Look, Motion, and Gestures
 
Navigation Architecture Component
Navigation Architecture ComponentNavigation Architecture Component
Navigation Architecture Component
 
Action bar
Action barAction bar
Action bar
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose world
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJava
 
Saindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender androidSaindo da zona de conforto… resolvi aprender android
Saindo da zona de conforto… resolvi aprender android
 
Managing Activity Backstack
Managing Activity BackstackManaging Activity Backstack
Managing Activity Backstack
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 
Managing parallelism using coroutines
Managing parallelism using coroutinesManaging parallelism using coroutines
Managing parallelism using coroutines
 
Handling action bar in Android
Handling action bar in AndroidHandling action bar in Android
Handling action bar in Android
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 

En vedette

Day1 what is android(print)
Day1 what is android(print)Day1 what is android(print)
Day1 what is android(print)
Dongchul Shin
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
Krazy Koder
 
Android notification
Android notificationAndroid notification
Android notification
Krazy Koder
 

En vedette (9)

Android Dialogs Tutorial
Android Dialogs TutorialAndroid Dialogs Tutorial
Android Dialogs Tutorial
 
Android-dialogs in android-chapter14
Android-dialogs in android-chapter14Android-dialogs in android-chapter14
Android-dialogs in android-chapter14
 
Alertdialog in android
Alertdialog in androidAlertdialog in android
Alertdialog in android
 
Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)Android Lab Test : Creating a dialog Yes/No (english)
Android Lab Test : Creating a dialog Yes/No (english)
 
Day1 what is android(print)
Day1 what is android(print)Day1 what is android(print)
Day1 what is android(print)
 
2310 b xd
2310 b xd2310 b xd
2310 b xd
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
Android notification
Android notificationAndroid notification
Android notification
 
Goodbye progress dialog mess on Android
Goodbye progress dialog mess on AndroidGoodbye progress dialog mess on Android
Goodbye progress dialog mess on Android
 

Similaire à Android basic 3 Dialogs

New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
nidhileena
 

Similaire à Android basic 3 Dialogs (20)

Day 5
Day 5Day 5
Day 5
 
MVC meets Monad
MVC meets MonadMVC meets Monad
MVC meets Monad
 
Androidaop 170105090257
Androidaop 170105090257Androidaop 170105090257
Androidaop 170105090257
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Google Web Toolkit
Google Web ToolkitGoogle Web Toolkit
Google Web Toolkit
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
안드로이드 세미나 2
안드로이드 세미나 2안드로이드 세미나 2
안드로이드 세미나 2
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
안드로이드 세미나 2
안드로이드 세미나 2안드로이드 세미나 2
안드로이드 세미나 2
 
Angular2: Quick overview with 2do app example
Angular2: Quick overview with 2do app exampleAngular2: Quick overview with 2do app example
Angular2: Quick overview with 2do app example
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
20180721 code defragment
20180721 code defragment20180721 code defragment
20180721 code defragment
 
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022JavaScript Iteration Protocols - Workshop NodeConf EU 2022
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
 
Practical
PracticalPractical
Practical
 
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super PowersJDD 2016 - Philippe Charrière -  Golo, The Tiny Language That Gives Super Powers
JDD 2016 - Philippe Charrière - Golo, The Tiny Language That Gives Super Powers
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
New microsoft office word document
New microsoft office word documentNew microsoft office word document
New microsoft office word document
 
Calculon
CalculonCalculon
Calculon
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 

Plus de Eakapong Kattiya (8)

(31 July 2013) iOS Basic Development Day 2 Human interface design
(31 July 2013) iOS Basic Development Day 2 Human interface design (31 July 2013) iOS Basic Development Day 2 Human interface design
(31 July 2013) iOS Basic Development Day 2 Human interface design
 
Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )Evrdi : Social Diary ( iOS and Android )
Evrdi : Social Diary ( iOS and Android )
 
Android Basic Development Day 1 Introduction & ADT
Android Basic Development Day 1 Introduction & ADTAndroid Basic Development Day 1 Introduction & ADT
Android Basic Development Day 1 Introduction & ADT
 
iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework
iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework
iOS Basic Development Day 2 - Objective-C 2.0 & iOS Framework
 
(1 July 2013) iOS Basic Development Day 5 - Submit to App Store
(1 July 2013) iOS Basic Development Day 5 - Submit to App Store(1 July 2013) iOS Basic Development Day 5 - Submit to App Store
(1 July 2013) iOS Basic Development Day 5 - Submit to App Store
 
Iphone developer advance twitter
Iphone developer advance   twitterIphone developer advance   twitter
Iphone developer advance twitter
 
iOS Advance Development - Social Media
iOS Advance Development - Social MediaiOS Advance Development - Social Media
iOS Advance Development - Social Media
 
Iphone developer advance location based
Iphone developer advance location basedIphone developer advance location based
Iphone developer advance location based
 

Dernier

Dernier (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Android basic 3 Dialogs

  • 1. Basic Programming Dialogs by Eakapong Kattiya Monday, July 15, 13
  • 2. 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
  • 3. by Eakapong Kattiya Alerts Alerts without title bar Alerts with title bar Monday, July 15, 13
  • 4. by Eakapong Kattiya Basic Buttons Buttons Borderless Buttons Buttons Monday, July 15, 13
  • 5. 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
  • 6. 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
  • 7. by Eakapong Kattiya Dialogs 1. Optional Title 2. Content area 3.Action button Monday, July 15, 13
  • 8. by Eakapong Kattiya Text Fields : EditText Single line & Multi line Text field types Text selection Monday, July 15, 13
  • 9. 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
  • 10. by Eakapong Kattiya Switches Radio Buttons On/Off Switches Checkboxes Monday, July 15, 13
  • 11. 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
  • 12. 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
  • 13. by Eakapong Kattiya Index Scrolling Scroll Indicator Scrolls Monday, July 15, 13
  • 14. by Eakapong Kattiya Pickers Space considerations Date & Time pickers Monday, July 15, 13
  • 15. 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
  • 16. 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
  • 17. @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
  • 18. 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
  • 19. by Eakapong Kattiya Popups (>API 11) Monday, July 15, 13
  • 20. by Eakapong Kattiya Spinners Spinners in forms Spinners in action bars (>API 11) Monday, July 15, 13
  • 21. 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
  • 22. 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
  • 23. by Eakapong Kattiya Gestures Touch Long press Swipe Drag Double touch Pinch open Pinch close Monday, July 15, 13
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. @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
  • 29. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. by Eakapong Kattiya Seek Bars Monday, July 15, 13