Android Tutorial - UI Dialog
Dialog Helper
package de.wathoserver.android.dragoid.util; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; public class DialogHelper { public static Dialog createDialogById(Context context, int id) { switch (id) { case UrlParsingActivity.DIALOG_PROGRESS: ProgressDialog pd = new ProgressDialog(context); pd.setTitle("Fortschritt"); pd.setMessage("Lade HTML-Seite..."); pd.setIndeterminate(true); return pd; default: return null; } } }
Use AlertDialog to inform exception
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final AlertDialog.Builder adb = new AlertDialog.Builder(this); final EditText addressfield = (EditText) findViewById(R.id.address); final Button button = (Button) findViewById(R.id.launchmap); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { // Perform action on click String address = addressfield.getText().toString(); address = address.replace(' ', '+'); Intent geoIntent = new Intent( android.content.Intent.ACTION_VIEW, Uri .parse("geo:0,0?q=" + address)); startActivity(geoIntent); } catch (Exception e) { AlertDialog ad = adb.create(); ad.setMessage("Failed to Launch"); ad.show(); } } }); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Please enter your home address." /> <EditText android:id="@+id/address" android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoText="true" /> <Button android:id="@+id/launchmap" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Map" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Unlocking Android" /> </LinearLayout>
Add option item to Alert dialog and get user selection result
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Test extends Activity { AlertDialog actions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Activity"); Button button = new Button(this); button.setText("Click for Options"); button.setOnClickListener(buttonListener); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose an Option"); String[] options = { "A", "B", "C" }; builder.setItems(options, actionListener); builder.setNegativeButton("Cancel", null); actions = builder.create(); setContentView(button); } DialogInterface.OnClickListener actionListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // Delete break; case 1: // Copy break; case 2: // Edit break; default: break; } } }; View.OnClickListener buttonListener = new View.OnClickListener() { @Override public void onClick(View v) { actions.show(); } }; }
Add some padding to keep the dialog borders away
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Activity"); TextView tv = new TextView(this); tv.setText("I'm Really An Activity!"); tv.setPadding(15, 15, 15, 15); setContentView(tv); } }
package com.commonsware.android.prefdialogs; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class DialogsDemo extends Activity { private static final int EDIT_ID = Menu.FIRST+2; private TextView checkbox=null; private TextView ringtone=null; private TextView checkbox2=null; private TextView text=null; private TextView list=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); checkbox=(TextView)findViewById(R.id.checkbox); ringtone=(TextView)findViewById(R.id.ringtone); checkbox2=(TextView)findViewById(R.id.checkbox2); text=(TextView)findViewById(R.id.text); list=(TextView)findViewById(R.id.list); } @Override public void onResume() { super.onResume(); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false)).toString()); ringtone.setText(prefs.getString("ringtone", "<unset>")); checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false)).toString()); text.setText(prefs.getString("text", "<unset>")); list.setText(prefs.getString("list", "<unset>")); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit Prefs") .setIcon(R.drawable.misc) .setAlphabeticShortcut('e'); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case EDIT_ID: startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } } //src\com\commonsware\android\prefdialogs\EditPreferences.java package com.commonsware.android.prefdialogs; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <TextView android:text="Checkbox:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox" /> </TableRow> <TableRow> <TextView android:text="Ringtone:" android:paddingRight="5px" /> <TextView android:id="@+id/ringtone" /> </TableRow> <TableRow> <TextView android:text="Checkbox #2:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox2" /> </TableRow> <TableRow> <TextView android:text="Text:" android:paddingRight="5px" /> <TextView android:id="@+id/text" /> </TableRow> <TableRow> <TextView android:text="List Selection:" android:paddingRight="5px" /> <TextView android:id="@+id/list" /> </TableRow> </TableLayout> //res\values\arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="cities"> <item>Philadelphia</item> <item>Pittsburgh</item> <item>Allentown/Bethlehem</item> <item>Erie</item> <item>Reading</item> <item>Scranton</item> <item>Lancaster</item> <item>Altoona</item> <item>Harrisburg</item> </string-array> <string-array name="airport_codes"> <item>PHL</item> <item>PIT</item> <item>ABE</item> <item>ERI</item> <item>RDG</item> <item>AVP</item> <item>LNS</item> <item>AOO</item> <item>MDT</item> </string-array> </resources> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">DialogsDemo</string> <string name="checkbox">checkbox</string> <string name="ringtone">ringtone</string> <string name="checkbox2">checkbox2</string> <string name="text">text</string> <string name="list">list</string> </resources> //res\xml\preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Simple Preferences"> <CheckBoxPreference android:key="checkbox" android:title="Checkbox Preference" android:summary="Check it on, check it off" /> <RingtonePreference android:key="ringtone" android:title="Ringtone Preference" android:showDefault="true" android:showSilent="true" android:summary="Pick a tone, any tone" /> </PreferenceCategory> <PreferenceCategory android:title="Detail Screens"> <PreferenceScreen android:key="detail" android:title="Detail Screen" android:summary="Additional preferences held in another page"> <CheckBoxPreference android:key="checkbox2" android:title="Another Checkbox" android:summary="On. Off. It really doesn't matter." /> </PreferenceScreen> </PreferenceCategory> <PreferenceCategory android:title="Other Preferences"> <EditTextPreference android:key="text" android:title="Text Entry Dialog" android:summary="Click to pop up a field for entry" android:dialogTitle="Enter something useful" /> <ListPreference android:key="list" android:title="Selection Dialog" android:summary="Click to pop up a list to choose from" android:entries="@array/cities" android:entryValues="@array/airport_codes" android:dialogTitle="Choose a Pennsylvania city" /> </PreferenceCategory> </PreferenceScreen>
Show dialog
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import android.app.ProgressDialog; import android.os.Handler; import android.os.Message; public class Test extends Activity { CharSequence[] items = { "Google", "Apple", "Microsoft" }; boolean[] itemsChecked = new boolean [items.length]; private ProgressDialog _progressDialog; private int _progress = 0; private Handler _progressHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn = (Button) findViewById(R.id.btn_dialog); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(1); _progress = 0; _progressDialog.setProgress(0); _progressHandler.sendEmptyMessage(0); } }); _progressHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); if (_progress >= 100) { _progressDialog.dismiss(); } else { _progress++; _progressDialog.incrementProgressBy(1); _progressHandler.sendEmptyMessageDelayed(0, 100); } } }; } @Override protected Dialog onCreateDialog(int id) { switch (id) { case 0: return new AlertDialog.Builder(this) .setIcon(R.drawable.icon) .setTitle("This is a dialog with some simple text...") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }) .setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), items[which] + (isChecked ? " checked!": " unchecked!"), Toast.LENGTH_SHORT).show(); } } ) .create(); case 1: _progressDialog = new ProgressDialog(this); _progressDialog.setIcon(R.drawable.icon); _progressDialog.setTitle("Downloading files..."); _progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); _progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Hide", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Hide clicked!", Toast.LENGTH_SHORT).show(); } }); _progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }); return _progressDialog; } return null; } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/btn_dialog" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Click to display a dialog" /> </LinearLayout>
Dialog layout
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Test extends Activity { private static final int DIALOG1 = 1; private static final int DIALOG2 = 2; private static final int DIALOG4 = 4; private static final int DIALOG3 = 3; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG1: return buildDialog1(Test.this); case DIALOG2: return buildDialog2(Test.this); case DIALOG3: return buildDialog3(Test.this); case DIALOG4: return buildDialog4(Test.this); } return null; } protected void onPrepareDialog(int id, Dialog dialog){ if(id==DIALOG1){ setTitle("5"); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.row); Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG1); } }); Button buttons2 = (Button) findViewById(R.id.buttons2); buttons2.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG2); } }); Button button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG3); } }); Button button4 = (Button) findViewById(R.id.button4); button4.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(DIALOG4); } }); } private Dialog buildDialog1(Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.icon); builder.setTitle("asdf"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("1"); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("2"); } }); return builder.create(); } private Dialog buildDialog2(Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.icon); builder.setTitle("asdf"); builder.setMessage("asdf"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("OK"); } }); builder.setNeutralButton("OK 2", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("title 2"); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("cancel"); } }); return builder.create(); } private Dialog buildDialog3(Context context) { LayoutInflater inflater = LayoutInflater.from(this); final View textEntryView = inflater.inflate( R.layout.add_edit, null); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setIcon(R.drawable.icon); builder.setTitle("text_entry"); builder.setView(textEntryView); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("3"); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { setTitle("4"); } }); return builder.create(); } private Dialog buildDialog4(Context context) { ProgressDialog dialog = new ProgressDialog(context); dialog.setTitle("4"); dialog.setMessage("4"); return dialog; } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> //row.xml <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="1" /> <Button android:id="@+id/buttons2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="2" /> <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="3" /> <Button android:id="@+id/button4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="4" /> </LinearLayout> </ScrollView> //add_edit.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/username_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="UserName" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/username_edit" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:capitalize="none" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/password_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="Password" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/password_edit" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:capitalize="none" android:password="true" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout>
Layout dialog with xml layout file
package app.test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.location.Location; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import java.util.Date; import java.text.SimpleDateFormat; import android.location.Location; class Quake { private Date date; private String details; private Location location; private double magnitude; private String link; public Date getDate() { return date; } public String getDetails() { return details; } public Location getLocation() { return location; } public double getMagnitude() { return magnitude; } public String getLink() { return link; } public Quake(Date _d, String _det, Location _loc, double _mag, String _link) { date = _d; details = _det; location = _loc; magnitude = _mag; link = _link; } @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("HH.mm"); return sdf.format(date) + ": " + magnitude + " " + details; } } public class Test extends Activity { static final private int QUAKE_DIALOG = 1; static final private int MENU_UPDATE = Menu.FIRST; ListView earthquakeListView; ArrayAdapter<Quake> aa; ArrayList<Quake> earthquakes = new ArrayList<Quake>(); Quake selectedQuake; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); earthquakeListView = (ListView)this.findViewById(R.id.earthquakeListView); earthquakeListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> _av, View _v, int _index, long _id) { selectedQuake = earthquakes.get(_index); showDialog(QUAKE_DIALOG); } }); aa = new ArrayAdapter<Quake>(getApplicationContext(), android.R.layout.simple_list_item_1, earthquakes); earthquakeListView.setAdapter(aa); refreshEarthquakes(); } private void refreshEarthquakes() { URL url; try { url = new URL("http://earthquake.usgs.gov/eqcenter/catalogs/1day-M2.5.xml"); URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(in); Element docEle = dom.getDocumentElement(); earthquakes.clear(); NodeList nl = docEle.getElementsByTagName("entry"); if (nl != null && nl.getLength() > 0) { for (int i = 0 ; i < nl.getLength(); i++) { Element entry = (Element)nl.item(i); Element title = (Element)entry.getElementsByTagName("title").item(0); Element g = (Element)entry.getElementsByTagName("georss:point").item(0); Element when = (Element)entry.getElementsByTagName("updated").item(0); Element link = (Element)entry.getElementsByTagName("link").item(0); String details = title.getFirstChild().getNodeValue(); String hostname = "http://earthquake.usgs.gov"; String linkString = hostname + link.getAttribute("href"); String point = g.getFirstChild().getNodeValue(); String dt = when.getFirstChild().getNodeValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'"); Date qdate = new GregorianCalendar(0,0,0).getTime(); try { qdate = sdf.parse(dt); } catch (ParseException e) { e.printStackTrace(); } String[] location = point.split(" "); Location l = new Location("dummyGPS"); l.setLatitude(Double.parseDouble(location[0])); l.setLongitude(Double.parseDouble(location[1])); String magnitudeString = details.split(" ")[1]; int end = magnitudeString.length()-1; double magnitude = Double.parseDouble(magnitudeString.substring(0, end)); details = details.split(",")[1].trim(); Quake quake = new Quake(qdate, details, l, magnitude, linkString); addNewQuake(quake); } } } } catch (Exception e) { e.printStackTrace(); } finally { } } private void addNewQuake(Quake _quake) { earthquakes.add(_quake); aa.notifyDataSetChanged(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_UPDATE, Menu.NONE, "update"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case (MENU_UPDATE): { refreshEarthquakes(); return true; } } return false; } @Override public Dialog onCreateDialog(int id) { switch(id) { case (QUAKE_DIALOG) : LayoutInflater li = LayoutInflater.from(this); View quakeDetailsView = li.inflate(R.layout.row, null); AlertDialog.Builder quakeDialog = new AlertDialog.Builder(this); quakeDialog.setTitle("Quake Time"); quakeDialog.setView(quakeDetailsView); return quakeDialog.create(); } return null; } @Override public void onPrepareDialog(int id, Dialog dialog) { switch(id) { case (QUAKE_DIALOG) : SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String dateString = sdf.format(selectedQuake.getDate()); String quakeText = "Mangitude " + selectedQuake.getMagnitude() + "\n" + selectedQuake.getDetails() + "\n" + selectedQuake.getLink(); AlertDialog quakeDialog = (AlertDialog)dialog; quakeDialog.setTitle(dateString); TextView tv = (TextView)quakeDialog.findViewById(R.id.quakeDetailsTextView); if (tv != null) tv.setText(quakeText); break; } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/earthquakeListView" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> //row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10sp"> <TextView android:id="@+id/quakeDetailsTextView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textSize="14sp" android:autoLink="all" /> </LinearLayout>
extends DialogFragment
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.widget.Toast; class AlertDialogFragment extends DialogFragment implements DialogInterface.OnClickListener { public static AlertDialogFragment newInstance(String message) { AlertDialogFragment adf = new AlertDialogFragment(); Bundle bundle = new Bundle(); bundle.putString("alert-message", message); adf.setArguments(bundle); return adf; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setCancelable(true); int style = DialogFragment.STYLE_NORMAL, theme = 0; setStyle(style, theme); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder b = new AlertDialog.Builder(getActivity()); b.setTitle("Alert!!"); b.setPositiveButton("Ok", this); b.setNegativeButton("Cancel", this); b.setMessage(this.getArguments().getString("alert-message")); return b.create(); } public void onClick(DialogInterface dialog, int which) { OnDialogDoneListener act = (OnDialogDoneListener) getActivity(); boolean cancelled = false; if (which == AlertDialog.BUTTON_NEGATIVE) { cancelled = true; } act.onDialogDone(getTag(), cancelled, "Alert dismissed"); } } interface OnDialogDoneListener { public void onDialogDone(String tag, boolean cancelled, CharSequence message); } public class Test extends Activity implements OnDialogDoneListener { public static final String LOGTAG = "DialogFragmentDemo"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); FragmentManager.enableDebugLogging(true); FragmentTransaction ft = getFragmentManager().beginTransaction(); AlertDialogFragment pdf = AlertDialogFragment .newInstance("Enter Something"); pdf.show(ft, "alert"); } public void onDialogDone(String tag, boolean cancelled, CharSequence message) { String s = tag + " responds with: " + message; if (cancelled) s = tag + " was cancelled by the user"; Toast.makeText(this, s, Toast.LENGTH_LONG).show(); Log.v(LOGTAG, s); } }
Color Picker Dialog
package app.test; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.EmbossMaskFilter; import android.graphics.MaskFilter; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Picture; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.SweepGradient; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.AttributeSet; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; public class Test extends GraphicsActivity implements ColorPickerDialog.OnColorChangedListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyView(this)); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(0xFFFF0000); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(12); mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f); mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL); } private Paint mPaint; private MaskFilter mEmboss; private MaskFilter mBlur; public void colorChanged(int color) { mPaint.setColor(color); } public class MyView extends View { private static final float MINP = 0.25f; private static final float MAXP = 0.75f; private Bitmap mBitmap; private Canvas mCanvas; private Path mPath; private Paint mBitmapPaint; public MyView(Context c) { super(c); mPath = new Path(); mBitmapPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(0xFFAAAAAA); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.drawPath(mPath, mPaint); } private float mX, mY; private static final float TOUCH_TOLERANCE = 4; private void touch_start(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX = x; mY = y; } } private void touch_up() { mPath.lineTo(mX, mY); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw mPath.reset(); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } } private static final int COLOR_MENU_ID = Menu.FIRST; private static final int EMBOSS_MENU_ID = Menu.FIRST + 1; private static final int BLUR_MENU_ID = Menu.FIRST + 2; private static final int ERASE_MENU_ID = Menu.FIRST + 3; private static final int SRCATOP_MENU_ID = Menu.FIRST + 4; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, COLOR_MENU_ID, 0, "Color").setShortcut('3', 'c'); menu.add(0, EMBOSS_MENU_ID, 0, "Emboss").setShortcut('4', 's'); menu.add(0, BLUR_MENU_ID, 0, "Blur").setShortcut('5', 'z'); menu.add(0, ERASE_MENU_ID, 0, "Erase").setShortcut('5', 'z'); menu.add(0, SRCATOP_MENU_ID, 0, "SrcATop").setShortcut('5', 'z'); /**** * Is this the mechanism to extend with filter effects? Intent intent = * new Intent(null, getIntent().getData()); * intent.addCategory(Intent.CATEGORY_ALTERNATIVE); * menu.addIntentOptions( Menu.ALTERNATIVE, 0, new ComponentName(this, * NotesList.class), null, intent, 0, null); *****/ return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { mPaint.setXfermode(null); mPaint.setAlpha(0xFF); switch (item.getItemId()) { case COLOR_MENU_ID: new ColorPickerDialog(this, this, mPaint.getColor()).show(); return true; case EMBOSS_MENU_ID: if (mPaint.getMaskFilter() != mEmboss) { mPaint.setMaskFilter(mEmboss); } else { mPaint.setMaskFilter(null); } return true; case BLUR_MENU_ID: if (mPaint.getMaskFilter() != mBlur) { mPaint.setMaskFilter(mBlur); } else { mPaint.setMaskFilter(null); } return true; case ERASE_MENU_ID: mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); return true; case SRCATOP_MENU_ID: mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); mPaint.setAlpha(0x80); return true; } return super.onOptionsItemSelected(item); } } class ColorPickerDialog extends Dialog { public interface OnColorChangedListener { void colorChanged(int color); } private OnColorChangedListener mListener; private int mInitialColor; private static class ColorPickerView extends View { private Paint mPaint; private Paint mCenterPaint; private final int[] mColors; private OnColorChangedListener mListener; ColorPickerView(Context c, OnColorChangedListener l, int color) { super(c); mListener = l; mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 }; Shader s = new SweepGradient(0, 0, mColors, null); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setShader(s); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(32); mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCenterPaint.setColor(color); mCenterPaint.setStrokeWidth(5); } private boolean mTrackingCenter; private boolean mHighlightCenter; @Override protected void onDraw(Canvas canvas) { float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f; canvas.translate(CENTER_X, CENTER_X); canvas.drawOval(new RectF(-r, -r, r, r), mPaint); canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint); if (mTrackingCenter) { int c = mCenterPaint.getColor(); mCenterPaint.setStyle(Paint.Style.STROKE); if (mHighlightCenter) { mCenterPaint.setAlpha(0xFF); } else { mCenterPaint.setAlpha(0x80); } canvas.drawCircle(0, 0, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint); mCenterPaint.setStyle(Paint.Style.FILL); mCenterPaint.setColor(c); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2); } private static final int CENTER_X = 100; private static final int CENTER_Y = 100; private static final int CENTER_RADIUS = 32; private int floatToByte(float x) { int n = java.lang.Math.round(x); return n; } private int pinToByte(int n) { if (n < 0) { n = 0; } else if (n > 255) { n = 255; } return n; } private int ave(int s, int d, float p) { return s + java.lang.Math.round(p * (d - s)); } private int interpColor(int colors[], float unit) { if (unit <= 0) { return colors[0]; } if (unit >= 1) { return colors[colors.length - 1]; } float p = unit * (colors.length - 1); int i = (int) p; p -= i; // now p is just the fractional part [0...1) and i is the index int c0 = colors[i]; int c1 = colors[i + 1]; int a = ave(Color.alpha(c0), Color.alpha(c1), p); int r = ave(Color.red(c0), Color.red(c1), p); int g = ave(Color.green(c0), Color.green(c1), p); int b = ave(Color.blue(c0), Color.blue(c1), p); return Color.argb(a, r, g, b); } private int rotateColor(int color, float rad) { float deg = rad * 180 / 3.1415927f; int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); ColorMatrix cm = new ColorMatrix(); ColorMatrix tmp = new ColorMatrix(); cm.setRGB2YUV(); tmp.setRotate(0, deg); cm.postConcat(tmp); tmp.setYUV2RGB(); cm.postConcat(tmp); final float[] a = cm.getArray(); int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b); int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b); int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b); return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig), pinToByte(ib)); } private static final float PI = 3.1415926f; @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX() - CENTER_X; float y = event.getY() - CENTER_Y; boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mTrackingCenter = inCenter; if (inCenter) { mHighlightCenter = true; invalidate(); break; } case MotionEvent.ACTION_MOVE: if (mTrackingCenter) { if (mHighlightCenter != inCenter) { mHighlightCenter = inCenter; invalidate(); } } else { float angle = (float) java.lang.Math.atan2(y, x); // need to turn angle [-PI ... PI] into unit [0....1] float unit = angle / (2 * PI); if (unit < 0) { unit += 1; } mCenterPaint.setColor(interpColor(mColors, unit)); invalidate(); } break; case MotionEvent.ACTION_UP: if (mTrackingCenter) { if (inCenter) { mListener.colorChanged(mCenterPaint.getColor()); } mTrackingCenter = false; // so we draw w/o halo invalidate(); } break; } return true; } } public ColorPickerDialog(Context context, OnColorChangedListener listener, int initialColor) { super(context); mListener = listener; mInitialColor = initialColor; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(int color) { mListener.colorChanged(color); dismiss(); } }; setContentView(new ColorPickerView(getContext(), l, mInitialColor)); setTitle("Pick a Color"); } } class GraphicsActivity extends Activity { // set to true to test Picture private static final boolean TEST_PICTURE = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void setContentView(View view) { if (TEST_PICTURE) { ViewGroup vg = new PictureLayout(this); vg.addView(view); view = vg; } super.setContentView(view); } } class PictureLayout extends ViewGroup { private final Picture mPicture = new Picture(); public PictureLayout(Context context) { super(context); } public PictureLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void addView(View child) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child); } @Override public void addView(View child, int index) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index); } @Override public void addView(View child, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, params); } @Override public void addView(View child, int index, LayoutParams params) { if (getChildCount() > 1) { throw new IllegalStateException( "PictureLayout can host only one direct child"); } super.addView(child, index, params); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int count = getChildCount(); int maxHeight = 0; int maxWidth = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { measureChild(child, widthMeasureSpec, heightMeasureSpec); } } maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingTop() + getPaddingBottom(); Drawable drawable = getBackground(); if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.getMinimumHeight()); maxWidth = Math.max(maxWidth, drawable.getMinimumWidth()); } setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), resolveSize(maxHeight, heightMeasureSpec)); } private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx, float sy) { canvas.save(); canvas.translate(x, y); canvas.clipRect(0, 0, w, h); canvas.scale(0.5f, 0.5f); canvas.scale(sx, sy, w, h); canvas.drawPicture(mPicture); canvas.restore(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight())); mPicture.endRecording(); int x = getWidth() / 2; int y = getHeight() / 2; if (false) { canvas.drawPicture(mPicture); } else { drawPict(canvas, 0, 0, x, y, 1, 1); drawPict(canvas, x, 0, x, y, -1, 1); drawPict(canvas, 0, y, x, y, 1, -1); drawPict(canvas, x, y, x, y, -1, -1); } } @Override public ViewParent invalidateChildInParent(int[] location, Rect dirty) { location[0] = getLeft(); location[1] = getTop(); dirty.set(0, 0, getWidth(), getHeight()); return getParent(); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = super.getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childLeft = getPaddingLeft(); final int childTop = getPaddingTop(); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } }
Dialog Yes No Message
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_MESSAGE: return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("alert_dialog_two_buttons_title") .setPositiveButton("alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNegativeButton("alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do some stuff */ } }) .create(); } return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_YES_NO_MESSAGE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog Yes No Old School Message
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_OLD_SCHOOL_MESSAGE: return new AlertDialog.Builder(Test.this, AlertDialog.THEME_TRADITIONAL) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("alert_dialog_two_buttons_title") .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .create(); } return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_YES_NO_OLD_SCHOOL_MESSAGE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_HOLO_LIGHT_MESSAGE: return new AlertDialog.Builder(Test.this, AlertDialog.THEME_HOLO_LIGHT) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_two_buttons_title") .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .create(); } return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_YES_NO_HOLO_LIGHT_MESSAGE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog Yes No Long Message
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_LONG_MESSAGE: return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_two_buttons_msg") .setMessage("R.string.alert_dialog_two_buttons2_msg") .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNeutralButton("R.string.alert_dialog_something", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Something so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_YES_NO_LONG_MESSAGE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_YES_NO_ULTRA_LONG_MESSAGE: return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_two_buttons_msg") .setMessage("R.string.alert_dialog_two_buttons2ultra_msg") .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNeutralButton("R.string.alert_dialog_something", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Something so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Cancel so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_YES_NO_ULTRA_LONG_MESSAGE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog with List of value
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_LIST: return new AlertDialog.Builder(Test.this) .setTitle("R.string.select_dialog") .setItems(1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* User clicked so do some stuff */ String[] items = new String[]{"a","b"}; new AlertDialog.Builder(Test.this) .setMessage("You selected: " + which + " , " + items[which]) .show(); } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_LIST); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog with Progress
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_PROGRESS: mProgressDialog = new ProgressDialog(Test.this); mProgressDialog.setIconAttribute(android.R.attr.alertDialogIcon); mProgressDialog.setTitle("R.string.select_dialog"); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setMax(MAX_PROGRESS); mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "R.string.alert_dialog_hide", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */ } }); mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */ } }); return mProgressDialog; } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_PROGRESS); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog with Single Choice
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SINGLE_CHOICE: return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_single_choice") .setSingleChoiceItems(new String[]{""}, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked on a radio button do some stuff */ } }) .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_SINGLE_CHOICE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog Multiple Choice
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MULTIPLE_CHOICE: return new AlertDialog.Builder(Test.this) .setIcon(R.drawable.icon) .setTitle("R.string.alert_dialog_multi_choice") .setMultiChoiceItems(new String[]{}, new boolean[]{false, true, false, true, false, false, false}, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { /* User clicked on a check box do some stuff */ } }) .setPositiveButton("alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_MULTIPLE_CHOICE); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog Multiple Choice Cursor
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MULTIPLE_CHOICE_CURSOR: String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.SEND_TO_VOICEMAIL }; Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null); return new AlertDialog.Builder(Test.this) .setIcon(R.drawable.icon) .setTitle("R.string.alert_dialog_multi_choice_cursor") .setMultiChoiceItems(cursor, ContactsContract.Contacts.SEND_TO_VOICEMAIL, ContactsContract.Contacts.DISPLAY_NAME, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { Toast.makeText(Test.this, "Readonly Demo Only - Data will not be updated", Toast.LENGTH_SHORT).show(); } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_MULTIPLE_CHOICE_CURSOR); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } }
Dialog with Text Entry
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_TEXT_ENTRY: // This example shows how to add a custom layout to an AlertDialog LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.row, null); return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_text_entry") .setView(textEntryView) .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_MULTIPLE_CHOICE_CURSOR); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } } //row.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2008 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/username_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="alert_dialog_username" android:gravity="left" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/username_edit" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/password_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="alert_dialog_password" android:gravity="left" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/password_edit" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" android:password="true" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout>
Dialog with Xml layout
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.database.Cursor; import android.provider.ContactsContract; /** * Example of how to use an {@link android.app.AlertDialog}. * <h3>Test</h3> <p>This demonstrates the different ways the AlertDialog can be used.</p> <h4>Demo</h4> App/Dialog/Alert Dialog <h4>Source files</h4> * <table class="LinkTable"> * <tr> * <td >src/com.example.android.apis/app/Test.java</td> * <td >The Alert Dialog Samples implementation</td> * </tr> * <tr> * <td >/res/any/layout/alert_dialog.xml</td> * <td >Defines contents of the screen</td> * </tr> * </table> */ public class Test extends Activity { private static final int DIALOG_YES_NO_MESSAGE = 1; private static final int DIALOG_YES_NO_LONG_MESSAGE = 2; private static final int DIALOG_LIST = 3; private static final int DIALOG_PROGRESS = 4; private static final int DIALOG_SINGLE_CHOICE = 5; private static final int DIALOG_MULTIPLE_CHOICE = 6; private static final int DIALOG_TEXT_ENTRY = 7; private static final int DIALOG_MULTIPLE_CHOICE_CURSOR = 8; private static final int DIALOG_YES_NO_ULTRA_LONG_MESSAGE = 9; private static final int DIALOG_YES_NO_OLD_SCHOOL_MESSAGE = 10; private static final int DIALOG_YES_NO_HOLO_LIGHT_MESSAGE = 11; private static final int MAX_PROGRESS = 100; private ProgressDialog mProgressDialog; private int mProgress; private Handler mProgressHandler; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_TEXT_ENTRY: // This example shows how to add a custom layout to an AlertDialog LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.row, null); return new AlertDialog.Builder(Test.this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("R.string.alert_dialog_text_entry") .setView(textEntryView) .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK so do some stuff */ } }) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do some stuff */ } }) .create(); } return null; } /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView(int)} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); showDialog(DIALOG_MULTIPLE_CHOICE_CURSOR); mProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (mProgress >= MAX_PROGRESS) { mProgressDialog.dismiss(); } else { mProgress++; mProgressDialog.incrementProgressBy(1); mProgressHandler.sendEmptyMessageDelayed(0, 100); } } }; } } //row.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2008 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/username_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="alert_dialog_username" android:gravity="left" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/username_edit" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/password_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:text="alert_dialog_password" android:gravity="left" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/password_edit" android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_marginLeft="20dip" android:layout_marginRight="20dip" android:scrollHorizontally="true" android:autoText="false" android:capitalize="none" android:gravity="fill_horizontal" android:password="true" android:textAppearance="?android:attr/textAppearanceMedium" /> </LinearLayout>
Dialog Activity
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; /** * <h3>Dialog Activity</h3> * * <p>This demonstrates the how to write an activity that looks like * a pop-up dialog.</p> */ public class Test extends Activity { /** * Initialization of the Activity after it is first created. Must at least * call {@link android.app.Activity#setContentView setContentView()} to * describe what is to be displayed in the screen. */ @Override protected void onCreate(Bundle savedInstanceState) { // Be sure to call the super class. super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_LEFT_ICON); // See assets/res/any/layout/dialog_activity.xml for this // view layout definition, which is being set here as // the content of our screen. setContentView(R.layout.main); getWindow().setTitle("This is just a test"); getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert); Button button = (Button)findViewById(R.id.add); button.setOnClickListener(mAddContentListener); button = (Button)findViewById(R.id.remove); button.setOnClickListener(mRemoveContentListener); } private OnClickListener mAddContentListener = new OnClickListener() { public void onClick(View v) { LinearLayout layout = (LinearLayout)findViewById(R.id.inner_content); ImageView iv = new ImageView(Test.this); iv.setImageDrawable(getResources().getDrawable(R.drawable.icon)); iv.setPadding(4, 4, 4, 4); layout.addView(iv); } }; private OnClickListener mRemoveContentListener = new OnClickListener() { public void onClick(View v) { LinearLayout layout = (LinearLayout)findViewById(R.id.inner_content); int num = layout.getChildCount(); if (num > 0) { layout.removeViewAt(num-1); } } }; } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="4dp" android:gravity="center_horizontal"> <!-- Message to show to use. --> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical|center_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" android:text="dialog_activity_text"/> <!-- Container in which we are going to add and remove views, to demonstrate how the layout adjusts based on size. --> <LinearLayout android:id="@+id/inner_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingTop="4dp" android:paddingBottom="4dp"> </LinearLayout> <!-- Alert dialog style buttons along the bottom. --> <LinearLayout style="?android:attr/buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:measureWithLargestChild="true"> <Button style="?android:attr/buttonBarButtonStyle" android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="dialog_activity_add" /> <Button style="?android:attr/buttonBarButtonStyle" android:id="@+id/remove" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="dialog_activity_remove" /> </LinearLayout> </LinearLayout>
Demonstrates how to show an AlertDialog that is managed by a Fragment.
package app.test; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * Demonstrates how to show an AlertDialog that is managed by a Fragment. */ public class Test extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); View tv = findViewById(R.id.text); ((TextView)tv).setText("Example of displaying an alert dialog with a DialogFragment"); // Watch for button clicks. Button button = (Button)findViewById(R.id.show); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(); } }); } void showDialog() { DialogFragment newFragment = MyAlertDialogFragment.newInstance(1); newFragment.show(getFragmentManager(), "dialog"); } public void doPositiveClick() { // Do stuff here. Log.i("FragmentAlertDialog", "Positive click!"); } public void doNegativeClick() { // Do stuff here. Log.i("FragmentAlertDialog", "Negative click!"); } public static class MyAlertDialogFragment extends DialogFragment { public static MyAlertDialogFragment newInstance(int title) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putInt("title", title); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt("title"); return new AlertDialog.Builder(getActivity()) .setIcon(R.drawable.icon) .setTitle(title) .setPositiveButton("R.string.alert_dialog_ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ((Test)getActivity()).doPositiveClick(); } } ) .setNegativeButton("R.string.alert_dialog_cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ((Test)getActivity()).doNegativeClick(); } } ) .create(); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Top-level content view for the simple fragment sample. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip" android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical|center_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" android:gravity="top|center_horizontal" /> <Button android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="show"> <requestFocus /> </Button> </LinearLayout>
package com.example.android.apis.app; import com.example.android.apis.R; import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class FragmentDialog extends Activity { int mStackLevel = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_dialog); View tv = findViewById(R.id.text); ((TextView)tv).setText("Example of displaying dialogs with a DialogFragment. " + "Press the show button below to see the first dialog; pressing " + "successive show buttons will display other dialog styles as a " + "stack, with dismissing or back going to the previous dialog."); // Watch for button clicks. Button button = (Button)findViewById(R.id.show); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(); } }); if (savedInstanceState != null) { mStackLevel = savedInstanceState.getInt("level"); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("level", mStackLevel); } void showDialog() { mStackLevel++; // DialogFragment.show() will take care of adding the fragment // in a transaction. We also want to remove any currently showing // dialog, so make our own transaction and take care of that here. FragmentTransaction ft = getFragmentManager().beginTransaction(); Fragment prev = getFragmentManager().findFragmentByTag("dialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); // Create and show the dialog. DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel); newFragment.show(ft, "dialog"); } static String getNameForNum(int num) { switch ((num-1)%6) { case 1: return "STYLE_NO_TITLE"; case 2: return "STYLE_NO_FRAME"; case 3: return "STYLE_NO_INPUT (this window can't receive input, so " + "you will need to press the bottom show button)"; case 4: return "STYLE_NORMAL with dark fullscreen theme"; case 5: return "STYLE_NORMAL with light theme"; case 6: return "STYLE_NO_TITLE with light theme"; case 7: return "STYLE_NO_FRAME with light theme"; case 8: return "STYLE_NORMAL with light fullscreen theme"; } return "STYLE_NORMAL"; } public static class MyDialogFragment extends DialogFragment { int mNum; /** * Create a new instance of MyDialogFragment, providing "num" * as an argument. */ static MyDialogFragment newInstance(int num) { MyDialogFragment f = new MyDialogFragment(); // Supply num input as an argument. Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments().getInt("num"); // Pick a style based on the num. int style = DialogFragment.STYLE_NORMAL, theme = 0; switch ((mNum-1)%6) { case 1: style = DialogFragment.STYLE_NO_TITLE; break; case 2: style = DialogFragment.STYLE_NO_FRAME; break; case 3: style = DialogFragment.STYLE_NO_INPUT; break; case 4: style = DialogFragment.STYLE_NORMAL; break; case 5: style = DialogFragment.STYLE_NORMAL; break; case 6: style = DialogFragment.STYLE_NO_TITLE; break; case 7: style = DialogFragment.STYLE_NO_FRAME; break; case 8: style = DialogFragment.STYLE_NORMAL; break; } switch ((mNum-1)%6) { case 4: theme = android.R.style.Theme_Holo; break; case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break; case 6: theme = android.R.style.Theme_Holo_Light; break; case 7: theme = android.R.style.Theme_Holo_Light_Panel; break; case 8: theme = android.R.style.Theme_Holo_Light; break; } setStyle(style, theme); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_dialog, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText("Dialog #" + mNum + ": using style " + getNameForNum(mNum)); // Watch for button clicks. Button button = (Button)v.findViewById(R.id.show); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { // When button is clicked, call up to owning activity. ((FragmentDialog)getActivity()).showDialog(); } }); return v; } } }
Demonstrates the use of progress dialogs.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.os.Bundle; import android.view.View; import android.widget.Button; /** * Demonstrates the use of progress dialogs. Uses {@link Activity#onCreateDialog} * and {@link Activity#showDialog} to ensure the dialogs will be properly saved * and restored. */ public class ProgressBar3 extends Activity { ProgressDialog mDialog1; ProgressDialog mDialog2; private static final int DIALOG1_KEY = 0; private static final int DIALOG2_KEY = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.progressbar_3); Button button = (Button) findViewById(R.id.showIndeterminate); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG1_KEY); } }); button = (Button) findViewById(R.id.showIndeterminateNoTitle); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DIALOG2_KEY); } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG1_KEY: { ProgressDialog dialog = new ProgressDialog(this); dialog.setTitle("Indeterminate"); dialog.setMessage("Please wait while loading..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } case DIALOG2_KEY: { ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("Please wait while loading..."); dialog.setIndeterminate(true); dialog.setCancelable(true); return dialog; } } return null; } } //layout/progressbar_3.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/showIndeterminate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_3_indeterminate" /> <Button android:id="@+id/showIndeterminateNoTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_3_indeterminate_no_title" /> </LinearLayout>
File open dialog
//package com.FileBrowser; import java.io.File; import java.util.ArrayList; import java.util.Collections; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; class OpenDialogLayout extends LinearLayout { public OpenDialogLayout(Context context) { super(context); init(context); } public OpenDialogLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void setItemLayout(View view) { view.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F)); } private void setListLayout(View view) { view.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); } private void init(Context context) { setOrientation(LinearLayout.VERTICAL); setListLayout(this); _tvPath = new TextView(context); setItemLayout(_tvPath); _tvPath.setText("Path: "); _etFile = new EditText(context); setItemLayout(_etFile); _etFile.setEnabled(false); _etFile.setFocusable(false); _FileList = new FileList(context); setListLayout(_FileList); _FileList.setPath("/"); _FileList.setFocusable(true); _FileList.setOnPathChangedListener(_OnPathChanged); _FileList.setOnFileSelected(_OnFileSelected); addView(_tvPath); addView(_etFile); addView(_FileList); setFocusable(true); setFocusableInTouchMode(true); } private TextView _tvPath = null; private EditText _etFile = null; private FileList _FileList = null; public String getPath() { return _tvPath.getText().toString(); } public String getFileName() { return _etFile.getText().toString(); } private OnPathChangedListener _OnPathChanged = new OnPathChangedListener() { public void onChanged(String path) { _tvPath.setText("Path: " + path); _etFile.setText(""); } }; private OnFileSelectedListener _OnFileSelected = new OnFileSelectedListener() { public void onSelected(String path, String fileName) { _etFile.setText(fileName); } }; } public class OpenDialog { public OpenDialog(Context context) { _OpenDialogLayout = new OpenDialogLayout(context); _Dialog = new AlertDialog.Builder(context); _Dialog.setTitle("Open Dialog"); _Dialog.setView(_OpenDialogLayout); _Dialog.setPositiveButton("Ok", _OnPositiveClick); _Dialog.setNegativeButton("Cancel", _OnNegativeClick); } private Builder _Dialog = null; private OpenDialogLayout _OpenDialogLayout = null; // Event private OnFileSelectedListener _OnFileSelected = null; private OnNotifyEventListener _OnCanceled = null; public void Show() { _Dialog.show(); } public void setOnFileSelected(OnFileSelectedListener value) { _OnFileSelected = value; } public OnFileSelectedListener getOnFileSelected() { return _OnFileSelected; } public void setOnCanceled(OnNotifyEventListener value) { _OnCanceled = value; } public OnNotifyEventListener getOnCanceled() { return _OnCanceled; } private DialogInterface.OnClickListener _OnPositiveClick = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (_OnFileSelected != null) { _OnFileSelected.onSelected(_OpenDialogLayout.getPath(), _OpenDialogLayout.getFileName()); } } }; private DialogInterface.OnClickListener _OnNegativeClick = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (_OnCanceled != null) { _OnCanceled.onNotify(OpenDialog.this); } } }; } interface OnFileSelectedListener { public void onSelected(String path, String fileName); } interface OnNotifyEventListener { public void onNotify(Object sender); } interface OnPathChangedListener { public void onChanged(String path); } class FileList extends ListView { public FileList(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public FileList(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public FileList(Context context) { super(context); init(context); } private void init(Context context) { _Context = context; setOnItemClickListener(_OnItemClick); } private Context _Context = null; private ArrayList<String> _List = new ArrayList<String>(); private ArrayList<String> _FolderList = new ArrayList<String>(); private ArrayList<String> _FileList = new ArrayList<String>(); private ArrayAdapter<String> _Adapter = null; // Property private String _Path = ""; // Event private OnPathChangedListener _OnPathChangedListener = null; private OnFileSelectedListener _OnFileSelectedListener = null; private boolean openPath(String path) { _FolderList.clear(); _FileList.clear(); File file = new File(path); File[] files = file.listFiles(); if (files == null) return false; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { _FolderList.add("<" + files[i].getName() + ">"); } else { _FileList.add(files[i].getName()); } } Collections.sort(_FolderList); Collections.sort(_FileList); _FolderList.add(0, "<..>"); return true; } private void updateAdapter() { _List.clear(); _List.addAll(_FolderList); _List.addAll(_FileList); _Adapter = new ArrayAdapter<String>(_Context, android.R.layout.simple_list_item_1, _List); setAdapter(_Adapter); } public void setPath(String value) { if (value.length() == 0) { value = "/"; } else { String lastChar = value.substring(value.length() - 1, value.length()); if (lastChar.matches("/") == false) value = value + "/"; } if (openPath(value)) { _Path = value; updateAdapter(); if (_OnPathChangedListener != null) _OnPathChangedListener.onChanged(value); } } public String getPath() { return _Path; } public void setOnPathChangedListener(OnPathChangedListener value) { _OnPathChangedListener = value; } public OnPathChangedListener getOnPathChangedListener() { return _OnPathChangedListener; } public void setOnFileSelected(OnFileSelectedListener value) { _OnFileSelectedListener = value; } public OnFileSelectedListener getOnFileSelected() { return _OnFileSelectedListener; } public String DelteRight(String value, String border) { String list[] = value.split(border); String result = ""; for (int i = 0; i < list.length; i++) { result = result + list[i] + border; } return result; } private String delteLastFolder(String value) { String list[] = value.split("/"); String result = ""; for (int i = 0; i < list.length - 1; i++) { result = result + list[i] + "/"; } return result; } private String getRealPathName(String newPath) { String path = newPath.substring(1, newPath.length() - 1); if (path.matches("..")) { return delteLastFolder(_Path); } else { return _Path + path + "/"; } } private AdapterView.OnItemClickListener _OnItemClick = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) { String fileName = getItemAtPosition(position).toString(); if (fileName.matches("<.*>")) { setPath(getRealPathName(fileName)); } else { if (_OnFileSelectedListener != null) _OnFileSelectedListener.onSelected(_Path, fileName); } } }; }
Show error AlertDialog
//package com.neugent.aethervoice.log; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnKeyListener; import android.view.KeyEvent; import android.view.View; /** * @author Amando Jose Quinto II The class that shows the error dialog box. */ public class ErrorAlert implements OnKeyListener{ private final Context mContext; public ErrorAlert(final Context context) { mContext = context; } public void showErrorDialog(final String title, final String message) { AlertDialog aDialog = new AlertDialog.Builder(mContext).setMessage(message).setTitle(title) .setNeutralButton("Close", new OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { //Prevent to finish activity, if user clicks about. if (!title.equalsIgnoreCase("About") && !title.equalsIgnoreCase("Directory Error") && !title.equalsIgnoreCase("View")) { ((Activity) mContext).finish(); } } }).create(); aDialog.setOnKeyListener(this); aDialog.show(); } @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ //disable the back button } return true; } }
extends DialogPreference
//package org.ametro.util; import android.content.Context; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; public class BarPreference extends DialogPreference implements SeekBar.OnSeekBarChangeListener { private static final String androidns = "http://schemas.android.com/apk/res/android"; private SeekBar mBar; private TextView mMessageText, mValueText; private String mPostfix; private int mDefault = 0; private int mMax = 100; private int mValue = 0; public BarPreference(Context context, AttributeSet attrs) { super(context, attrs); mPostfix = attrs.getAttributeValue(androidns, "postfix"); mDefault = attrs.getAttributeIntValue(androidns, "defaultValue", 0); mMax = attrs.getAttributeIntValue(androidns, "max", 100); } public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) { String valueText = String.valueOf(value); mValueText.setText(mPostfix == null ? valueText : valueText + mPostfix); if (shouldPersist()){ persistInt(value); } callChangeListener(new Integer(value)); } public void onStartTrackingTouch(SeekBar seek) { } public void onStopTrackingTouch(SeekBar seek) { } protected View onCreateDialogView() { LinearLayout container = new LinearLayout(getContext()); container.setOrientation(LinearLayout.VERTICAL); container.setPadding(10, 5, 10, 5); mMessageText = new TextView(getContext()); mMessageText.setText(getSummary()); container.addView(mMessageText); mValueText = new TextView(getContext()); mValueText.setGravity(Gravity.CENTER_HORIZONTAL); container.addView(mValueText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); mBar = new SeekBar(getContext()); mBar.setOnSeekBarChangeListener(this); mBar.setPadding(5, 0, 5, 0); container.addView(mBar, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); if (shouldPersist()){ mValue = getPersistedInt(mDefault); } mBar.setMax(mMax); mBar.setProgress(mValue); return container; } protected void onBindDialogView(View v) { super.onBindDialogView(v); mBar.setMax(mMax); mBar.setProgress(mValue); } protected void onSetInitialValue(boolean restore, Object defaultValue) { super.onSetInitialValue(restore, defaultValue); if (restore) mValue = shouldPersist() ? getPersistedInt(mDefault) : 0; else mValue = (Integer) defaultValue; } }
Show Notification Alert Dialog
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; class Notifications { public static void infoDialog(Context ctx, String title, String message) { AlertDialog.Builder b = new AlertDialog.Builder(ctx); b.setMessage(message); b.setCancelable(false); b.setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); b.setTitle(title); AlertDialog ad = b.create(); ad.show(); } }
Text Dialog
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; /** * Class with support functions * * @author Hooiveld */ final class Utils { public static void textDialog(Context context, String title, String text) { new AlertDialog .Builder(context) .setTitle(title) .setMessage(text) .setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } } ) .show(); } }
Create Chang Log Dialog
import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; class DialogUtil { public static final Dialog createChangLogDialog(Context context) { AlertDialog.Builder builder; builder = new AlertDialog.Builder(context); builder.setTitle("title"); final String[] changes = new String[]{}; final StringBuilder buf = new StringBuilder(changes[0]); for (int i = 1; i < changes.length; i++) { buf.append("\n\n"); buf.append(changes[i]); } builder.setIcon(android.R.drawable.ic_menu_info_details); builder.setMessage(buf.toString()); builder.setCancelable(true); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { //write current version dialog.cancel(); } }); return builder.create(); } }
Show Title And Message Dialog
//package com.geobloc.shared; import android.app.AlertDialog; import android.content.Context; import android.widget.Toast; class Utilities { /* * Type for the "Widget" */ public enum WidgetType {LABEL, STRING, INT, BUTTON, CHECKBOX}; /* * Displays a Toast. The context parameter is filled with getApplicationContext() from the Activity * you're calling this from. Duration is with Toast.LENGTH_SHORT or Toast.LENGTH_LONG */ public static void showToast(Context context, String message, int duration) { Toast toast = Toast.makeText(context, message, duration); toast.show(); } public static void showTitleAndMessageDialog(Context context, String title, String message) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(title); alert.setMessage(message); alert.setPositiveButton("OK", null); alert.show(); } }
//package com.awl.tumlabs.twitter.android; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import android.app.AlertDialog.Builder; import android.content.Context; import android.os.Bundle; class Util { protected static Bundle parseUrl(String url, String protocol) { url = url.replace(protocol, "http://"); try { URL u = new URL(url); Bundle b = decodeUrl(u.getQuery()); b.putAll(decodeUrl(u.getRef())); return b; } catch (MalformedURLException e) { return new Bundle(); } } protected static Bundle decodeUrl(String s) { Bundle params = new Bundle(); if (s != null) { String array[] = s.split("&"); for (String parameter : array) { String v[] = parameter.split("="); params.putString(URLDecoder.decode(v[0]), URLDecoder.decode(v[1])); } } return params; } protected static void showAlert(Context context, String title, String text) { Builder alertBuilder = new Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(text); alertBuilder.create().show(); } }
Error Dialog Wrapper
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** * @author Andrei Samkov */ class ErrorDialogWrapper implements DialogInterface.OnClickListener { private AlertDialog dialog; public ErrorDialogWrapper(Activity activity, Exception e) { this(activity, e.getMessage()); } public ErrorDialogWrapper(Activity activity, String e) { dialog = new AlertDialog.Builder(activity) .setMessage(e) .setPositiveButton("OK", this) .create(); } public void show() { dialog.show(); } public void onClick(DialogInterface dialogInterface, int i) { dialog.cancel(); } }
Ok Dialog Wrapper
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** * @author Andrei Samkov */ public class OkDialogWrapper implements DialogInterface.OnClickListener{ private AlertDialog dialog; public OkDialogWrapper(Activity activity, String text) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(text); builder.setPositiveButton("OK", this); dialog = builder.create(); } public void show(){ dialog.show(); } public void onClick(DialogInterface dialogInterface, int i) { dialog.cancel(); } }
//package net.vexelon.bgrates; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.net.URLConnection; import org.apache.http.util.ByteArrayBuffer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.KeyEvent; public class Utils { /** * Display an alert dialog * @param context * @param messageResId * @param titleResId */ public static void showAlertDialog(Context context, int messageResId, int titleResId) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); alertBuilder.setTitle( context.getResources().getString( titleResId)).setMessage( context.getResources().getString(messageResId)).setIcon(R.drawable.alert).setOnKeyListener( new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { dialog.dismiss(); return false; } }).create().show(); } }
AlertDialog Question
import android.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; class Utils { final static AlertDialog Question(Context context, int message_id, DialogInterface.OnClickListener yes_listener) { AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setMessage(message_id); dialog.setPositiveButton("yes", yes_listener); dialog.setNegativeButton("no", null); dialog.setCancelable(true); return dialog.show(); } }
import android.app.AlertDialog;
import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; class UIHelper { public static void openChangelogPopup(final Context context) { final AlertDialog.Builder builder = new AlertDialog.Builder(context) .setCancelable(true) .setTitle("Changelog") .setMessage("line.\n line") .setNeutralButton("App", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { final Intent intent = new Intent( Intent.ACTION_VIEW); intent.setData(Uri.parse("market://details?id=" + context.getPackageName())); context.startActivity(intent); } }). setPositiveButton("Close", null); final AlertDialog di = builder.create(); di.show(); } }
dialog Builder
import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; class DialogUtils { public static void dialogBuilder(Activity instance, String title, String message, final DialogCallBack callBack) { AlertDialog.Builder builder = new Builder(instance); builder.setMessage(message); builder.setTitle(title); builder.setPositiveButton("Positive", new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); callBack.callBack(); } }); builder.setNegativeButton("Negative", new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } } interface DialogCallBack { public void callBack(); }
A dialog that allows the user to select multiple entries.
//package ch.dissem.android.utils; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import java.util.ArrayList; import java.util.Collection; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; class MultiChoiceListAdapter<T> extends BaseAdapter { private Context ctx; private Collection<T> options; private Collection<T> selection; private List<T> filteredOptions; public MultiChoiceListAdapter(Context context, Collection<T> options, Collection<T> selection) { this.ctx = context; this.options = options; this.selection = selection; this.filteredOptions = new ArrayList<T>(options.size()); setFilter(null); } @Override public int getCount() { return filteredOptions.size(); } @Override public T getItem(int position) { return filteredOptions.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ChoiceView view; T item = getItem(position); boolean selected = selection.contains(item); if (convertView == null) { view = new ChoiceView(ctx, item, selected); } else { view = (ChoiceView) convertView; view.setItem(item, selected); } return view; } public void setFilter(String filter) { if (filter != null) filter = filter.toLowerCase(); filteredOptions.clear(); for (T item : selection) filteredOptions.add(item); for (T item : options) if (!selection.contains(item) && (filter == null || item.toString().toLowerCase() .contains(filter))) filteredOptions.add(item); } public class ChoiceView extends CheckBox implements OnCheckedChangeListener { private T object; public ChoiceView(Context context, T object, Boolean selected) { super(context); this.object = object; setOnCheckedChangeListener(this); setItem(object, selected); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (selection != null) { if (isChecked && !selection.contains(object)) selection.add(object); else if (!isChecked) selection.remove(object); } notifyDataSetChanged(); } public void setItem(T object, Boolean selected) { this.object = object; setChecked(selected); setText(object.toString()); } } } class MultiChoice<T> extends Dialog { private ListView listView; private Map<T, Boolean> optionsWithSelection; private Collection<T> options; private Collection<T> selection; public MultiChoice(Context context, Collection<T> options, Collection<T> selection) { super(context); this.options = options; this.selection = selection; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context ctx = getContext(); LinearLayout layout = new LinearLayout(ctx); layout.setOrientation(LinearLayout.VERTICAL); listView = new ListView(ctx); final MultiChoiceListAdapter<T> adapter; adapter = new MultiChoiceListAdapter<T>(ctx, options, selection); listView.setAdapter(adapter); if (options.size() > 10) { EditText search = new EditText(ctx); search.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER); search.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.setFilter(s.toString()); adapter.notifyDataSetChanged(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); layout.addView(search); } layout.addView(listView); setContentView(layout); } public Map<T, Boolean> getOptionsMap() { return optionsWithSelection; } public Set<T> getSelection() { Set<T> result = new LinkedHashSet<T>(); for (Entry<T, Boolean> e : optionsWithSelection.entrySet()) if (Boolean.TRUE.equals(e.getValue())) result.add(e.getKey()); return result; } }
Help Dialog Creator
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; class HelpDialogCreator { private static final String SHOWN_ALREADY = "SHOWN_ALREADY"; public static void helpDialog(Activity activity, String title, String helpContent, String backButtonTxt, boolean showOnlyOnce) { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(activity); boolean shownAlready = sp.getBoolean(SHOWN_ALREADY, false); if (!shownAlready || !showOnlyOnce) { new AlertDialog.Builder(activity) .setTitle(title) .setMessage(helpContent) .setPositiveButton(backButtonTxt, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialoginterface, int i) { } }).show(); Editor edit = sp.edit(); edit.putBoolean(SHOWN_ALREADY, true); edit.commit(); } } }
Color Select Dialog
//package com.hyperzsoft.utils; import android.app.Dialog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; public class ColorSelectDialog extends Dialog { public interface OnColorChangedListener { void colorChanged(String key, int color); } private OnColorChangedListener mListener; private int mInitialColor; private String mKey; public static class ColorPickerView extends View { private Paint mPaint; private float mCurrentHue = 0; private final int[] mHueBarColors = new int[258]; private OnColorChangedListener mListener; public void setColor(int color) { } public int getColor() { return getCurrentMainColor(); } ColorPickerView(Context c, OnColorChangedListener l, int color) { super(c); mListener = l; // Get the current hue from the current color and update the main color field float[] hsv = new float[3]; Color.colorToHSV(color, hsv); mCurrentHue = hsv[0]; // Initialize the colors of the hue slider bar int index = 0; for (float i=0; i<256; i += 256/42) // Red (#f00) to pink (#f0f) { mHueBarColors[index] = Color.rgb(255, 0, (int) i); index++; } for (float i=0; i<256; i += 256/42) // Pink (#f0f) to blue (#00f) { mHueBarColors[index] = Color.rgb(255-(int) i, 0, 255); index++; } for (float i=0; i<256; i += 256/42) // Blue (#00f) to light blue (#0ff) { mHueBarColors[index] = Color.rgb(0, (int) i, 255); index++; } for (float i=0; i<256; i += 256/42) // Light blue (#0ff) to green (#0f0) { mHueBarColors[index] = Color.rgb(0, 255, 255-(int) i); index++; } for (float i=0; i<256; i += 256/42) // Green (#0f0) to yellow (#ff0) { mHueBarColors[index] = Color.rgb((int) i, 255, 0); index++; } for (float i=0; i<256; i += 256/42) // Yellow (#ff0) to red (#f00) { mHueBarColors[index] = Color.rgb(255, 255-(int) i, 0); index++; } // Initializes the Paint that will draw the View mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setTextAlign(Paint.Align.CENTER); mPaint.setTextSize(12); } // Get the current selected color from the hue bar private int getCurrentMainColor() { int translatedHue = 255-(int)(mCurrentHue*255/360); int index = 0; for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb(255, 0, (int) i); index++; } for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb(255-(int) i, 0, 255); index++; } for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb(0, (int) i, 255); index++; } for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb(0, 255, 255-(int) i); index++; } for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb((int) i, 255, 0); index++; } for (float i=0; i<256; i += 256/42) { if (index == translatedHue) return Color.rgb(255, 255-(int) i, 0); index++; } return Color.RED; } @Override protected void onDraw(Canvas canvas) { int translatedHue = 255-(int)(mCurrentHue*255/360); // Display all the colors of the hue bar with lines for (int x=0; x<256; x++) { // If this is not the current selected hue, display the actual color if (translatedHue != x) { mPaint.setColor(mHueBarColors[x]); mPaint.setStrokeWidth(2); } else // else display a slightly larger black line { mPaint.setColor(Color.BLACK); mPaint.setStrokeWidth(3); } canvas.drawLine((x*2)+10, 0, (x*2)+10, 40, mPaint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //setMeasuredDimension(276, 60); setMeasuredDimension(532, 60); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) return true; float x = event.getX(); float y = event.getY(); //the touch event is located in the hue bar if (x > 10 && x < 522 && y > 0 && y < 40) { // Update the main field colors mCurrentHue = (255-(x/2))*360/255; mListener.colorChanged("", getCurrentMainColor()); // Force the redraw of the dialog invalidate(); } return true; } } public ColorSelectDialog(Context context, OnColorChangedListener listener, String key, int initialColor) { super(context); mListener = listener; mKey = key; mInitialColor = initialColor; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); OnColorChangedListener l = new OnColorChangedListener() { public void colorChanged(String key, int color) { mListener.colorChanged(mKey, color); dismiss(); } }; setContentView(new ColorPickerView(getContext(), l, mInitialColor)); setTitle("Select Color"); } }
Create MessageBox
import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import android.app.AlertDialog; class Tools { public static void MessageBox( final Context ctx, final String text) { Toast.makeText(ctx, text, Toast.LENGTH_LONG).show(); } }