Android Tutorial - 15 UI exemple 3
1-ListAdapter
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.ExpandableListView; import android.content.Context; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ExpandableListView list = new ExpandableListView(this); list.setGroupIndicator(null); list.setChildIndicator(null); String[] titles = {"A","B","C"}; String[] fruits = {"a1","a2"}; String[] veggies = {"b1","b2","b3"}; String[] meats = {"c1","c2"}; String[][] contents = {fruits,veggies,meats}; SimplerExpandableListAdapter adapter = new SimplerExpandableListAdapter(this, titles, contents); list.setAdapter(adapter); setContentView(list); } } class SimplerExpandableListAdapter extends BaseExpandableListAdapter { private Context mContext; private String[][] mContents; private String[] mTitles; public SimplerExpandableListAdapter(Context context, String[] titles, String[][] contents) { super(); if(titles.length != contents.length) { throw new IllegalArgumentException("Titles and Contents must be the same size."); } mContext = context; mContents = contents; mTitles = titles; } @Override public String getChild(int groupPosition, int childPosition) { return mContents[groupPosition][childPosition]; } @Override public long getChildId(int groupPosition, int childPosition) { return 0; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView row = (TextView)convertView; if(row == null) { row = new TextView(mContext); } row.setText(mContents[groupPosition][childPosition]); return row; } @Override public int getChildrenCount(int groupPosition) { return mContents[groupPosition].length; } @Override public String[] getGroup(int groupPosition) { return mContents[groupPosition]; } @Override public int getGroupCount() { return mContents.length; } @Override public long getGroupId(int groupPosition) { return 0; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView row = (TextView)convertView; if(row == null) { row = new TextView(mContext); } row.setTypeface(Typeface.DEFAULT_BOLD); row.setText(mTitles[groupPosition]); return row; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
//package net.matzat.android.hiberdroid.widget; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import java.util.ArrayList; import java.util.List; public abstract class GenericListAdapter<T> extends BaseAdapter { protected Context context; protected List<T> list; public GenericListAdapter(Context context) { super(); this.context = context; this.list = new ArrayList<T>(); } public GenericListAdapter(Context context, List<T> list) { super(); this.context = context; this.list = list; } public int getCount() { return list.size(); } public T getItem(int i) { return list.get(i); } public void setList(List<T> list) { this.list = list; this.notifyDataSetChanged(); } public abstract long getItemId(int i); public abstract View getView(int i, View view, ViewGroup viewGroup); }
A list view example where the data comes from a custom ListAdapter
package com.example.android.apis.view; import android.app.ListActivity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * A list view example where the * data comes from a custom * ListAdapter */ public class List6 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Use our own list adapter setListAdapter(new SpeechListAdapter(this)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { ((SpeechListAdapter)getListAdapter()).toggle(position); } /** * A sample ListAdapter that presents content * from arrays of speeches and text. * */ private class SpeechListAdapter extends BaseAdapter { public SpeechListAdapter(Context context) { mContext = context; } /** * The number of items in the list is determined by the number of speeches * in our array. * * @see android.widget.ListAdapter#getCount() */ public int getCount() { return mTitles.length; } /** * Since the data comes from an array, just returning * the index is sufficent to get at the data. If we * were using a more complex data structure, we * would return whatever object represents one * row in the list. * * @see android.widget.ListAdapter#getItem(int) */ public Object getItem(int position) { return position; } /** * Use the array index as a unique id. * @see android.widget.ListAdapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * Make a SpeechView to hold each row. * @see android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { SpeechView sv; if (convertView == null) { sv = new SpeechView(mContext, mTitles[position], mDialogue[position], mExpanded[position]); } else { sv = (SpeechView)convertView; sv.setTitle(mTitles[position]); sv.setDialogue(mDialogue[position]); sv.setExpanded(mExpanded[position]); } return sv; } public void toggle(int position) { mExpanded[position] = !mExpanded[position]; notifyDataSetChanged(); } /** * Remember our context so we can use it when constructing views. */ private Context mContext; /** * Our data, part 1. */ private String[] mTitles = { "Henry IV (1)", "Henry V", "Henry VIII", "Richard II", "Richard III", "Merchant of Venice", "Othello", "King Lear" }; /** * Our data, part 2. */ private String[] mDialogue = { "So shaken as we are, so wan with care," + "Find we a time for frighted peace to pant," + "And breathe short-winded accents of new broils" + "To be commenced in strands afar remote." + "No more the thirsty entrance of this soil" + "Shall daub her lips with her own children's blood;" + "Nor more shall trenching war channel her fields," + "Nor bruise her flowerets with the armed hoofs" + "Of hostile paces: those opposed eyes," + "Which, like the meteors of a troubled heaven," + "All of one nature, of one substance bred," + "Did lately meet in the intestine shock" + "And furious close of civil butchery" + "Shall now, in mutual well-beseeming ranks," + "March all one way and be no more opposed" + "Against acquaintance, kindred and allies:" + "The edge of war, like an ill-sheathed knife," + "No more shall cut his master. Therefore, friends," + "As far as to the sepulchre of Christ," + "Whose soldier now, under whose blessed cross" + "We are impressed and engaged to fight," + "Forthwith a power of English shall we levy;" + "Whose arms were moulded in their mothers' womb" + "To chase these pagans in those holy fields" + "Over whose acres walk'd those blessed feet" + "Which fourteen hundred years ago were nail'd" + "For our advantage on the bitter cross." + "But this our purpose now is twelve month old," + "And bootless 'tis to tell you we will go:" + "Therefore we meet not now. Then let me hear" + "Of you, my gentle cousin Westmoreland," + "What yesternight our council did decree" + "In forwarding this dear expedience.", "Hear him but reason in divinity," + "And all-admiring with an inward wish" + "You would desire the king were made a prelate:" + "Hear him debate of commonwealth affairs," + "You would say it hath been all in all his study:" + "List his discourse of war, and you shall hear" + "A fearful battle render'd you in music:" + "Turn him to any cause of policy," + "The Gordian knot of it he will unloose," + "Familiar as his garter: that, when he speaks," + "The air, a charter'd libertine, is still," + "And the mute wonder lurketh in men's ears," + "To steal his sweet and honey'd sentences;" + "So that the art and practic part of life" + "Must be the mistress to this theoric:" + "Which is a wonder how his grace should glean it," + "Since his addiction was to courses vain," + "His companies unletter'd, rude and shallow," + "His hours fill'd up with riots, banquets, sports," + "And never noted in him any study," + "Any retirement, any sequestration" + "From open haunts and popularity.", "I come no more to make you laugh: things now," + "That bear a weighty and a serious brow," + "Sad, high, and working, full of state and woe," + "Such noble scenes as draw the eye to flow," + "We now present. Those that can pity, here" + "May, if they think it well, let fall a tear;" + "The subject will deserve it. Such as give" + "Their money out of hope they may believe," + "May here find truth too. Those that come to see" + "Only a show or two, and so agree" + "The play may pass, if they be still and willing," + "I'll undertake may see away their shilling" + "Richly in two short hours. Only they" + "That come to hear a merry bawdy play," + "A noise of targets, or to see a fellow" + "In a long motley coat guarded with yellow," + "Will be deceived; for, gentle hearers, know," + "To rank our chosen truth with such a show" + "As fool and fight is, beside forfeiting" + "Our own brains, and the opinion that we bring," + "To make that only true we now intend," + "Will leave us never an understanding friend." + "Therefore, for goodness' sake, and as you are known" + "The first and happiest hearers of the town," + "Be sad, as we would make ye: think ye see" + "The very persons of our noble story" + "As they were living; think you see them great," + "And follow'd with the general throng and sweat" + "Of thousand friends; then in a moment, see" + "How soon this mightiness meets misery:" + "And, if you can be merry then, I'll say" + "A man may weep upon his wedding-day.", "First, heaven be the record to my speech!" + "In the devotion of a subject's love," + "Tendering the precious safety of my prince," + "And free from other misbegotten hate," + "Come I appellant to this princely presence." + "Now, Thomas Mowbray, do I turn to thee," + "And mark my greeting well; for what I speak" + "My body shall make good upon this earth," + "Or my divine soul answer it in heaven." + "Thou art a traitor and a miscreant," + "Too good to be so and too bad to live," + "Since the more fair and crystal is the sky," + "The uglier seem the clouds that in it fly." + "Once more, the more to aggravate the note," + "With a foul traitor's name stuff I thy throat;" + "And wish, so please my sovereign, ere I move," + "What my tongue speaks my right drawn sword may prove.", "Now is the winter of our discontent" + "Made glorious summer by this sun of York;" + "And all the clouds that lour'd upon our house" + "In the deep bosom of the ocean buried." + "Now are our brows bound with victorious wreaths;" + "Our bruised arms hung up for monuments;" + "Our stern alarums changed to merry meetings," + "Our dreadful marches to delightful measures." + "Grim-visaged war hath smooth'd his wrinkled front;" + "And now, instead of mounting barded steeds" + "To fright the souls of fearful adversaries," + "He capers nimbly in a lady's chamber" + "To the lascivious pleasing of a lute." + "But I, that am not shaped for sportive tricks," + "Nor made to court an amorous looking-glass;" + "I, that am rudely stamp'd, and want love's majesty" + "To strut before a wanton ambling nymph;" + "I, that am curtail'd of this fair proportion," + "Cheated of feature by dissembling nature," + "Deformed, unfinish'd, sent before my time" + "Into this breathing world, scarce half made up," + "And that so lamely and unfashionable" + "That dogs bark at me as I halt by them;" + "Why, I, in this weak piping time of peace," + "Have no delight to pass away the time," + "Unless to spy my shadow in the sun" + "And descant on mine own deformity:" + "And therefore, since I cannot prove a lover," + "To entertain these fair well-spoken days," + "I am determined to prove a villain" + "And hate the idle pleasures of these days." + "Plots have I laid, inductions dangerous," + "By drunken prophecies, libels and dreams," + "To set my brother Clarence and the king" + "In deadly hate the one against the other:" + "And if King Edward be as true and just" + "As I am subtle, false and treacherous," + "This day should Clarence closely be mew'd up," + "About a prophecy, which says that 'G'" + "Of Edward's heirs the murderer shall be." + "Dive, thoughts, down to my soul: here" + "Clarence comes.", "To bait fish withal: if it will feed nothing else," + "it will feed my revenge. He hath disgraced me, and" + "hindered me half a million; laughed at my losses," + "mocked at my gains, scorned my nation, thwarted my" + "bargains, cooled my friends, heated mine" + "enemies; and what's his reason? I am a Jew. Hath" + "not a Jew eyes? hath not a Jew hands, organs," + "dimensions, senses, affections, passions? fed with" + "the same food, hurt with the same weapons, subject" + "to the same diseases, healed by the same means," + "warmed and cooled by the same winter and summer, as" + "a Christian is? If you prick us, do we not bleed?" + "if you tickle us, do we not laugh? if you poison" + "us, do we not die? and if you wrong us, shall we not" + "revenge? If we are like you in the rest, we will" + "resemble you in that. If a Jew wrong a Christian," + "what is his humility? Revenge. If a Christian" + "wrong a Jew, what should his sufferance be by" + "Christian example? Why, revenge. The villany you" + "teach me, I will execute, and it shall go hard but I" + "will better the instruction.", "Virtue! a fig! 'tis in ourselves that we are thus" + "or thus. Our bodies are our gardens, to the which" + "our wills are gardeners: so that if we will plant" + "nettles, or sow lettuce, set hyssop and weed up" + "thyme, supply it with one gender of herbs, or" + "distract it with many, either to have it sterile" + "with idleness, or manured with industry, why, the" + "power and corrigible authority of this lies in our" + "wills. If the balance of our lives had not one" + "scale of reason to poise another of sensuality, the" + "blood and baseness of our natures would conduct us" + "to most preposterous conclusions: but we have" + "reason to cool our raging motions, our carnal" + "stings, our unbitted lusts, whereof I take this that" + "you call love to be a sect or scion.", "Blow, winds, and crack your cheeks! rage! blow!" + "You cataracts and hurricanoes, spout" + "Till you have drench'd our steeples, drown'd the cocks!" + "You sulphurous and thought-executing fires," + "Vaunt-couriers to oak-cleaving thunderbolts," + "Singe my white head! And thou, all-shaking thunder," + "Smite flat the thick rotundity o' the world!" + "Crack nature's moulds, an germens spill at once," + "That make ingrateful man!" }; /** * Our data, part 3. */ private boolean[] mExpanded = { false, false, false, false, false, false, false, false }; } /** * We will use a SpeechView to display each speech. It's just a LinearLayout * with two text fields. * */ private class SpeechView extends LinearLayout { public SpeechView(Context context, String title, String dialogue, boolean expanded) { super(context); this.setOrientation(VERTICAL); // Here we build the child views in code. They could also have // been specified in an XML file. mTitle = new TextView(context); mTitle.setText(title); addView(mTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue = new TextView(context); mDialogue.setText(dialogue); addView(mDialogue, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue.setVisibility(expanded ? VISIBLE : GONE); } /** * Convenience method to set the title of a SpeechView */ public void setTitle(String title) { mTitle.setText(title); } /** * Convenience method to set the dialogue of a SpeechView */ public void setDialogue(String words) { mDialogue.setText(words); } /** * Convenience method to expand or hide the dialogue */ public void setExpanded(boolean expanded) { mDialogue.setVisibility(expanded ? VISIBLE : GONE); } private TextView mTitle; private TextView mDialogue; } }
package com.example.android.apis.view; import android.app.ListActivity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * A list view example where the * data comes from a custom * ListAdapter */ public class List6 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Use our own list adapter setListAdapter(new SpeechListAdapter(this)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { ((SpeechListAdapter)getListAdapter()).toggle(position); } /** * A sample ListAdapter that presents content * from arrays of speeches and text. * */ private class SpeechListAdapter extends BaseAdapter { public SpeechListAdapter(Context context) { mContext = context; } /** * The number of items in the list is determined by the number of speeches * in our array. * * @see android.widget.ListAdapter#getCount() */ public int getCount() { return mTitles.length; } /** * Since the data comes from an array, just returning * the index is sufficent to get at the data. If we * were using a more complex data structure, we * would return whatever object represents one * row in the list. * * @see android.widget.ListAdapter#getItem(int) */ public Object getItem(int position) { return position; } /** * Use the array index as a unique id. * @see android.widget.ListAdapter#getItemId(int) */ public long getItemId(int position) { return position; } /** * Make a SpeechView to hold each row. * @see android.widget.ListAdapter#getView(int, android.view.View, android.view.ViewGroup) */ public View getView(int position, View convertView, ViewGroup parent) { SpeechView sv; if (convertView == null) { sv = new SpeechView(mContext, mTitles[position], mDialogue[position], mExpanded[position]); } else { sv = (SpeechView)convertView; sv.setTitle(mTitles[position]); sv.setDialogue(mDialogue[position]); sv.setExpanded(mExpanded[position]); } return sv; } public void toggle(int position) { mExpanded[position] = !mExpanded[position]; notifyDataSetChanged(); } /** * Remember our context so we can use it when constructing views. */ private Context mContext; /** * Our data, part 1. */ private String[] mTitles = { "Henry IV (1)", "Henry V", "Henry VIII", "Richard II", "Richard III", "Merchant of Venice", "Othello", "King Lear" }; /** * Our data, part 2. */ private String[] mDialogue = { "So shaken as we are, so wan with care," + "Find we a time for frighted peace to pant," + "And breathe short-winded accents of new broils" + "To be commenced in strands afar remote." + "No more the thirsty entrance of this soil" + "Shall daub her lips with her own children's blood;" + "Nor more shall trenching war channel her fields," + "Nor bruise her flowerets with the armed hoofs" + "Of hostile paces: those opposed eyes," + "Which, like the meteors of a troubled heaven," + "All of one nature, of one substance bred," + "Did lately meet in the intestine shock" + "And furious close of civil butchery" + "Shall now, in mutual well-beseeming ranks," + "March all one way and be no more opposed" + "Against acquaintance, kindred and allies:" + "The edge of war, like an ill-sheathed knife," + "No more shall cut his master. Therefore, friends," + "As far as to the sepulchre of Christ," + "Whose soldier now, under whose blessed cross" + "We are impressed and engaged to fight," + "Forthwith a power of English shall we levy;" + "Whose arms were moulded in their mothers' womb" + "To chase these pagans in those holy fields" + "Over whose acres walk'd those blessed feet" + "Which fourteen hundred years ago were nail'd" + "For our advantage on the bitter cross." + "But this our purpose now is twelve month old," + "And bootless 'tis to tell you we will go:" + "Therefore we meet not now. Then let me hear" + "Of you, my gentle cousin Westmoreland," + "What yesternight our council did decree" + "In forwarding this dear expedience.", "Hear him but reason in divinity," + "And all-admiring with an inward wish" + "You would desire the king were made a prelate:" + "Hear him debate of commonwealth affairs," + "You would say it hath been all in all his study:" + "List his discourse of war, and you shall hear" + "A fearful battle render'd you in music:" + "Turn him to any cause of policy," + "The Gordian knot of it he will unloose," + "Familiar as his garter: that, when he speaks," + "The air, a charter'd libertine, is still," + "And the mute wonder lurketh in men's ears," + "To steal his sweet and honey'd sentences;" + "So that the art and practic part of life" + "Must be the mistress to this theoric:" + "Which is a wonder how his grace should glean it," + "Since his addiction was to courses vain," + "His companies unletter'd, rude and shallow," + "His hours fill'd up with riots, banquets, sports," + "And never noted in him any study," + "Any retirement, any sequestration" + "From open haunts and popularity.", "I come no more to make you laugh: things now," + "That bear a weighty and a serious brow," + "Sad, high, and working, full of state and woe," + "Such noble scenes as draw the eye to flow," + "We now present. Those that can pity, here" + "May, if they think it well, let fall a tear;" + "The subject will deserve it. Such as give" + "Their money out of hope they may believe," + "May here find truth too. Those that come to see" + "Only a show or two, and so agree" + "The play may pass, if they be still and willing," + "I'll undertake may see away their shilling" + "Richly in two short hours. Only they" + "That come to hear a merry bawdy play," + "A noise of targets, or to see a fellow" + "In a long motley coat guarded with yellow," + "Will be deceived; for, gentle hearers, know," + "To rank our chosen truth with such a show" + "As fool and fight is, beside forfeiting" + "Our own brains, and the opinion that we bring," + "To make that only true we now intend," + "Will leave us never an understanding friend." + "Therefore, for goodness' sake, and as you are known" + "The first and happiest hearers of the town," + "Be sad, as we would make ye: think ye see" + "The very persons of our noble story" + "As they were living; think you see them great," + "And follow'd with the general throng and sweat" + "Of thousand friends; then in a moment, see" + "How soon this mightiness meets misery:" + "And, if you can be merry then, I'll say" + "A man may weep upon his wedding-day.", "First, heaven be the record to my speech!" + "In the devotion of a subject's love," + "Tendering the precious safety of my prince," + "And free from other misbegotten hate," + "Come I appellant to this princely presence." + "Now, Thomas Mowbray, do I turn to thee," + "And mark my greeting well; for what I speak" + "My body shall make good upon this earth," + "Or my divine soul answer it in heaven." + "Thou art a traitor and a miscreant," + "Too good to be so and too bad to live," + "Since the more fair and crystal is the sky," + "The uglier seem the clouds that in it fly." + "Once more, the more to aggravate the note," + "With a foul traitor's name stuff I thy throat;" + "And wish, so please my sovereign, ere I move," + "What my tongue speaks my right drawn sword may prove.", "Now is the winter of our discontent" + "Made glorious summer by this sun of York;" + "And all the clouds that lour'd upon our house" + "In the deep bosom of the ocean buried." + "Now are our brows bound with victorious wreaths;" + "Our bruised arms hung up for monuments;" + "Our stern alarums changed to merry meetings," + "Our dreadful marches to delightful measures." + "Grim-visaged war hath smooth'd his wrinkled front;" + "And now, instead of mounting barded steeds" + "To fright the souls of fearful adversaries," + "He capers nimbly in a lady's chamber" + "To the lascivious pleasing of a lute." + "But I, that am not shaped for sportive tricks," + "Nor made to court an amorous looking-glass;" + "I, that am rudely stamp'd, and want love's majesty" + "To strut before a wanton ambling nymph;" + "I, that am curtail'd of this fair proportion," + "Cheated of feature by dissembling nature," + "Deformed, unfinish'd, sent before my time" + "Into this breathing world, scarce half made up," + "And that so lamely and unfashionable" + "That dogs bark at me as I halt by them;" + "Why, I, in this weak piping time of peace," + "Have no delight to pass away the time," + "Unless to spy my shadow in the sun" + "And descant on mine own deformity:" + "And therefore, since I cannot prove a lover," + "To entertain these fair well-spoken days," + "I am determined to prove a villain" + "And hate the idle pleasures of these days." + "Plots have I laid, inductions dangerous," + "By drunken prophecies, libels and dreams," + "To set my brother Clarence and the king" + "In deadly hate the one against the other:" + "And if King Edward be as true and just" + "As I am subtle, false and treacherous," + "This day should Clarence closely be mew'd up," + "About a prophecy, which says that 'G'" + "Of Edward's heirs the murderer shall be." + "Dive, thoughts, down to my soul: here" + "Clarence comes.", "To bait fish withal: if it will feed nothing else," + "it will feed my revenge. He hath disgraced me, and" + "hindered me half a million; laughed at my losses," + "mocked at my gains, scorned my nation, thwarted my" + "bargains, cooled my friends, heated mine" + "enemies; and what's his reason? I am a Jew. Hath" + "not a Jew eyes? hath not a Jew hands, organs," + "dimensions, senses, affections, passions? fed with" + "the same food, hurt with the same weapons, subject" + "to the same diseases, healed by the same means," + "warmed and cooled by the same winter and summer, as" + "a Christian is? If you prick us, do we not bleed?" + "if you tickle us, do we not laugh? if you poison" + "us, do we not die? and if you wrong us, shall we not" + "revenge? If we are like you in the rest, we will" + "resemble you in that. If a Jew wrong a Christian," + "what is his humility? Revenge. If a Christian" + "wrong a Jew, what should his sufferance be by" + "Christian example? Why, revenge. The villany you" + "teach me, I will execute, and it shall go hard but I" + "will better the instruction.", "Virtue! a fig! 'tis in ourselves that we are thus" + "or thus. Our bodies are our gardens, to the which" + "our wills are gardeners: so that if we will plant" + "nettles, or sow lettuce, set hyssop and weed up" + "thyme, supply it with one gender of herbs, or" + "distract it with many, either to have it sterile" + "with idleness, or manured with industry, why, the" + "power and corrigible authority of this lies in our" + "wills. If the balance of our lives had not one" + "scale of reason to poise another of sensuality, the" + "blood and baseness of our natures would conduct us" + "to most preposterous conclusions: but we have" + "reason to cool our raging motions, our carnal" + "stings, our unbitted lusts, whereof I take this that" + "you call love to be a sect or scion.", "Blow, winds, and crack your cheeks! rage! blow!" + "You cataracts and hurricanoes, spout" + "Till you have drench'd our steeples, drown'd the cocks!" + "You sulphurous and thought-executing fires," + "Vaunt-couriers to oak-cleaving thunderbolts," + "Singe my white head! And thou, all-shaking thunder," + "Smite flat the thick rotundity o' the world!" + "Crack nature's moulds, an germens spill at once," + "That make ingrateful man!" }; /** * Our data, part 3. */ private boolean[] mExpanded = { false, false, false, false, false, false, false, false }; } /** * We will use a SpeechView to display each speech. It's just a LinearLayout * with two text fields. * */ private class SpeechView extends LinearLayout { public SpeechView(Context context, String title, String dialogue, boolean expanded) { super(context); this.setOrientation(VERTICAL); // Here we build the child views in code. They could also have // been specified in an XML file. mTitle = new TextView(context); mTitle.setText(title); addView(mTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue = new TextView(context); mDialogue.setText(dialogue); addView(mDialogue, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mDialogue.setVisibility(expanded ? VISIBLE : GONE); } /** * Convenience method to set the title of a SpeechView */ public void setTitle(String title) { mTitle.setText(title); } /** * Convenience method to set the dialogue of a SpeechView */ public void setDialogue(String words) { mDialogue.setText(words); } /** * Convenience method to expand or hide the dialogue */ public void setExpanded(boolean expanded) { mDialogue.setVisibility(expanded ? VISIBLE : GONE); } private TextView mTitle; private TextView mDialogue; } }
package com.example.android.apis.view; import android.app.ListActivity; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.view.View; import android.widget.SimpleCursorAdapter; import android.widget.TextView; /** * A list view example where the * data comes from a cursor, and a * SimpleCursorListAdapter is used to map each item to a two-line * display. */ public class List3 extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get a cursor with all phones Cursor c = getContentResolver().query(Phone.CONTENT_URI, PHONE_PROJECTION, null, null, null); startManagingCursor(c); // Map Cursor columns to views defined in simple_list_item_2.xml SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c, new String[] { Phone.TYPE, Phone.NUMBER }, new int[] { android.R.id.text1, android.R.id.text2 }); //Used to display a readable string for the phone type adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { public boolean setViewValue(View view, Cursor cursor, int columnIndex) { //Let the adapter handle the binding if the column is not TYPE if (columnIndex != COLUMN_TYPE) { return false; } int type = cursor.getInt(COLUMN_TYPE); String label = null; //Custom type? Then get the custom label if (type == Phone.TYPE_CUSTOM) { label = cursor.getString(COLUMN_LABEL); } //Get the readable string String text = (String) Phone.getTypeLabel(getResources(), type, label); //Set text ((TextView) view).setText(text); return true; } }); setListAdapter(adapter); } private static final String[] PHONE_PROJECTION = new String[] { Phone._ID, Phone.TYPE, Phone.LABEL, Phone.NUMBER }; private static final int COLUMN_TYPE = 1;; private static final int COLUMN_LABEL = 2; }
extends BaseExpandableListAdapter
package com.example.android.apis.view; import android.app.ExpandableListActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.TextView; import android.widget.Toast; import android.widget.ExpandableListView.ExpandableListContextMenuInfo; import com.example.android.apis.R; /** * Demonstrates expandable lists using a custom {@link ExpandableListAdapter} * from {@link BaseExpandableListAdapter}. */ public class ExpandableList1 extends ExpandableListActivity { ExpandableListAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up our adapter mAdapter = new MyExpandableListAdapter(); setListAdapter(mAdapter); registerForContextMenu(getExpandableListView()); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.setHeaderTitle("Sample menu"); menu.add(0, 0, 0, R.string.expandable_list_sample_action); } @Override public boolean onContextItemSelected(MenuItem item) { ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) item.getMenuInfo(); String title = ((TextView) info.targetView).getText().toString(); int type = ExpandableListView.getPackedPositionType(info.packedPosition); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition); Toast.makeText(this, title + ": Child " + childPos + " clicked in group " + groupPos, Toast.LENGTH_SHORT).show(); return true; } else if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) { int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); Toast.makeText(this, title + ": Group " + groupPos + " clicked", Toast.LENGTH_SHORT).show(); return true; } return false; } /** * A simple adapter which maintains an ArrayList of photo resource Ids. * Each photo is displayed as an image. This adapter supports clearing the * list of photos and adding a new photo. * */ public class MyExpandableListAdapter extends BaseExpandableListAdapter { // Sample data set. children[i] contains the children (String[]) for groups[i]. private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" }; private String[][] children = { { "Arnold", "Barry", "Chuck", "David" }, { "Ace", "Bandit", "Cha-Cha", "Deuce" }, { "Fluffy", "Snuggles" }, { "Goldy", "Bubbles" } }; public Object getChild(int groupPosition, int childPosition) { return children[groupPosition][childPosition]; } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public int getChildrenCount(int groupPosition) { return children[groupPosition].length; } public TextView getGenericView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 64); TextView textView = new TextView(ExpandableList1.this); textView.setLayoutParams(lp); // Center the text vertically textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); // Set the text starting position textView.setPadding(36, 0, 0, 0); return textView; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView textView = getGenericView(); textView.setText(getChild(groupPosition, childPosition).toString()); return textView; } public Object getGroup(int groupPosition) { return groups[groupPosition]; } public int getGroupCount() { return groups.length; } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView textView = getGenericView(); textView.setText(getGroup(groupPosition).toString()); return textView; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public boolean hasStableIds() { return true; } } }
package com.commonsware.android.fancylists.seven; import android.database.DataSetObserver; import android.widget.ListAdapter; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; public class AdapterWrapper implements ListAdapter { ListAdapter delegate=null; public AdapterWrapper(ListAdapter delegate) { this.delegate=delegate; } public int getCount() { return(delegate.getCount()); } public Object getItem(int position) { return(delegate.getItem(position)); } public long getItemId(int position) { return(delegate.getItemId(position)); } public View getView(int position, View convertView, ViewGroup parent) { return(delegate.getView(position, convertView, parent)); } public void registerDataSetObserver(DataSetObserver observer) { delegate.registerDataSetObserver(observer); } public boolean hasStableIds() { return(delegate.hasStableIds()); } public boolean isEmpty() { return(delegate.isEmpty()); } public int getViewTypeCount() { return(delegate.getViewTypeCount()); } public int getItemViewType(int position) { return(delegate.getItemViewType(position)); } public void unregisterDataSetObserver(DataSetObserver observer) { delegate.unregisterDataSetObserver(observer); } public boolean areAllItemsEnabled() { return(delegate.areAllItemsEnabled()); } public boolean isEnabled(int position) { return(delegate.isEnabled(position)); } } //src\com\commonsware\android\fancylists\seven\RateListView.java /*** Copyright (c) 2008-2009 CommonsWare, LLC 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. */ package com.commonsware.android.fancylists.seven; import android.content.Context; import android.util.AttributeSet; import android.widget.ListAdapter; import android.widget.ListView; public class RateListView extends ListView { public RateListView(Context context) { super(context); } public RateListView(Context context, AttributeSet attrs) { super(context, attrs); } public RateListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setAdapter(ListAdapter adapter) { super.setAdapter(new RateableWrapper(getContext(), adapter)); } } //src\com\commonsware\android\fancylists\seven\RateListViewDemo.java package com.commonsware.android.fancylists.seven; import android.app.Activity; import android.os.Bundle; import android.app.ListActivity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.RatingBar; import android.widget.CompoundButton; import android.widget.ListView; public class RateListViewDemo extends ListActivity { String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items)); } } //src\com\commonsware\android\fancylists\seven\RateableWrapper.java package com.commonsware.android.fancylists.seven; import android.content.Context; import android.database.DataSetObserver; import android.widget.ListAdapter; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.RatingBar; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; public class RateableWrapper extends AdapterWrapper { Context ctxt=null; float[] rates=null; public RateableWrapper(Context ctxt, ListAdapter delegate) { super(delegate); this.ctxt=ctxt; this.rates=new float[delegate.getCount()]; for (int i=0;i<delegate.getCount();i++) { this.rates[i]=2.0f; } } public View getView(int position, View convertView, ViewGroup parent) { ViewWrapper wrap=null; View row=convertView; if (convertView==null) { LinearLayout layout=new LinearLayout(ctxt); RatingBar rate=new RatingBar(ctxt); rate.setNumStars(3); rate.setStepSize(1.0f); View guts=delegate.getView(position, null, parent); layout.setOrientation(LinearLayout.HORIZONTAL); rate.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT)); guts.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); RatingBar.OnRatingBarChangeListener l= new RatingBar.OnRatingBarChangeListener() { public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromTouch) { rates[(Integer)ratingBar.getTag()]=rating; } }; rate.setOnRatingBarChangeListener(l); layout.addView(rate); layout.addView(guts); wrap=new ViewWrapper(layout); wrap.setGuts(guts); layout.setTag(wrap); rate.setTag(new Integer(position)); rate.setRating(rates[position]); row=layout; } else { wrap=(ViewWrapper)convertView.getTag(); wrap.setGuts(delegate.getView(position, wrap.getGuts(), parent)); wrap.getRatingBar().setTag(new Integer(position)); wrap.getRatingBar().setRating(rates[position]); } return(row); } } //src\com\commonsware\android\fancylists\seven\ViewWrapper.java package com.commonsware.android.fancylists.seven; import android.view.View; import android.view.ViewGroup; import android.widget.RatingBar; class ViewWrapper { ViewGroup base; View guts=null; RatingBar rate=null; ViewWrapper(ViewGroup base) { this.base=base; } RatingBar getRatingBar() { if (rate==null) { rate=(RatingBar)base.getChildAt(0); } return(rate); } void setRatingBar(RatingBar rate) { this.rate=rate; } View getGuts() { if (guts==null) { guts=base.getChildAt(1); } return(guts); } void setGuts(View guts) { this.guts=guts; } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <com.commonsware.android.fancylists.seven.RateListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:drawSelectorOnTop="false" />
2-Progress
Using progress bar
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>
public class ProgressMonitor implements IProgressListener { private final ProgressMonitor mParentProgressMonitor; private final IProgressListener mListener; private int mSubMonitorRangeFrom = 0; private int mSubMonitorRangeTo = 100; private int mProgress = 0; public ProgressMonitor(final IProgressListener pListener) { this.mListener = pListener; this.mParentProgressMonitor = null; } public ProgressMonitor(final ProgressMonitor pParent){ this.mListener = null; this.mParentProgressMonitor = pParent; } public ProgressMonitor getParentProgressMonitor() { return this.mParentProgressMonitor; } public int getProgress() { return this.mProgress; } public void setSubMonitorRange(final int pSubMonitorRangeFrom, final int pSubMonitorRangeTo) { this.mSubMonitorRangeFrom = pSubMonitorRangeFrom; this.mSubMonitorRangeTo = pSubMonitorRangeTo; } @Override public void onProgressChanged(final int pProgress){ this.mProgress = pProgress; if(this.mParentProgressMonitor != null) { this.mParentProgressMonitor.onSubProgressChanged(pProgress); } else { this.mListener.onProgressChanged(pProgress); } } private void onSubProgressChanged(final int pSubProgress){ final int subRange = this.mSubMonitorRangeTo- this.mSubMonitorRangeFrom; final int subProgressInRange = this.mSubMonitorRangeFrom + (int)(subRange * pSubProgress / 100f); if(this.mParentProgressMonitor != null) { this.mParentProgressMonitor.onSubProgressChanged(subProgressInRange); }else{ this.mListener.onProgressChanged(subProgressInRange); } } } interface ProgressCallable<T> { public T call(final IProgressListener pProgressListener) throws Exception; } interface IProgressListener { public void onProgressChanged(final int pProgress); }
Use an indeterminate progress indicator in the window's title bar.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.View; import android.widget.Button; public class ProgressBar4 extends Activity { private boolean mToggleIndeterminate = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request progress bar requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.progressbar_4); setProgressBarIndeterminateVisibility(mToggleIndeterminate); Button button = (Button) findViewById(R.id.toggle); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mToggleIndeterminate = !mToggleIndeterminate; setProgressBarIndeterminateVisibility(mToggleIndeterminate); } }); } } //layout/progressbar_4.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/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_4_toggle" /> </LinearLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.Window; public class ProgressBar2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request for the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.progressbar_2); // Make sure the progress bar is visible setProgressBarVisibility(true); } } //layout/progressbar_2.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"> <ProgressBar android:id="@+android:id/progress_large" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ProgressBar android:id="@+android:id/progress" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ProgressBar android:id="@+android:id/progress_small" style="?android:attr/progressBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ProgressBar android:id="@+android:id/progress_small_title" style="?android:attr/progressBarStyleSmallTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Use progress bars as widgets and in the title bar. The progress bar in the title will be shown until the progress is complete, at which point it fades away.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.widget.Button; import android.widget.ProgressBar; import android.os.Bundle; import android.view.View; import android.view.Window; public class ProgressBar1 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Request the progress bar to be shown in the title requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.progressbar_1); setProgressBarVisibility(true); final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal); setProgress(progressHorizontal.getProgress() * 100); setSecondaryProgress(progressHorizontal.getSecondaryProgress() * 100); Button button = (Button) findViewById(R.id.increase); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { progressHorizontal.incrementProgressBy(1); // Title progress is in range 0..10000 setProgress(100 * progressHorizontal.getProgress()); } }); button = (Button) findViewById(R.id.decrease); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { progressHorizontal.incrementProgressBy(-1); // Title progress is in range 0..10000 setProgress(100 * progressHorizontal.getProgress()); } }); button = (Button) findViewById(R.id.increase_secondary); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { progressHorizontal.incrementSecondaryProgressBy(1); // Title progress is in range 0..10000 setSecondaryProgress(100 * progressHorizontal.getSecondaryProgress()); } }); button = (Button) findViewById(R.id.decrease_secondary); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { progressHorizontal.incrementSecondaryProgressBy(-1); // Title progress is in range 0..10000 setSecondaryProgress(100 * progressHorizontal.getSecondaryProgress()); } }); } } //layout/progressbar_1.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"> <ProgressBar android:id="@+id/progress_horizontal" style="?android:attr/progressBarStyleHorizontal" android:layout_width="200dip" android:layout_height="wrap_content" android:max="100" android:progress="50" android:secondaryProgress="75" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_default_progress" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/decrease" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_minus" /> <Button android:id="@+id/increase" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_plus" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_secondary_progress" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/decrease_secondary" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_minus" /> <Button android:id="@+id/increase_secondary" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="progressbar_1_plus" /> </LinearLayout> </LinearLayout>
Round ProgressBar vs Flat ProgressBar
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.CheckBox; public class Test extends Activity { CheckBox plain_cb; CheckBox serif_cb; CheckBox italic_cb; CheckBox bold_cb; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("ProgressBarActivity"); setContentView(R.layout.main); } } //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="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Round ProgressBar" /> <ProgressBar android:id="@+id/progress_bar" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flat ProgressBar" /> <ProgressBar android:id="@+id/progress_horizontal" style="?android:attr/progressBarStyleHorizontal" android:layout_width="200dip" android:layout_height="wrap_content" android:max="100" android:progress="50" android:secondaryProgress="75" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.ProgressBar; public class Test extends Activity { private static int progress; private ProgressBar progressBar; private int progressStatus = 0; private Handler handler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); progress = 0; progressBar = (ProgressBar) findViewById(R.id.progressbar); progressBar.setMax(200); new Thread(new Runnable() { public void run() { while (progressStatus < 200) { progressStatus = doSomeWork(); handler.post(new Runnable() { public void run() { progressBar.setProgress(progressStatus); } }); } handler.post(new Runnable() { public void run() { // ---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE--- progressBar.setVisibility(8); } }); } private int doSomeWork() { try { // ---simulate doing some work--- Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } return ++progress; } }).start(); } } //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" > <ProgressBar android:id="@+id/progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" /> </LinearLayout>
3-Spinner
package com.commonsware.android.selection; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; public class SpinnerDemo extends Activity implements AdapterView.OnItemSelectedListener { TextView selection; String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); selection=(TextView)findViewById(R.id.selection); Spinner spin=(Spinner)findViewById(R.id.spinner); spin.setOnItemSelectedListener(this); ArrayAdapter<String> aa=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items); aa.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); spin.setAdapter(aa); } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { selection.setText(items[position]); } public void onNothingSelected(AdapterView<?> parent) { selection.setText(""); } } //res\layout\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:id="@+id/selection" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> </LinearLayout>
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; public class Spinner1 extends Activity { void showToast(CharSequence msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.spinner_1); Spinner s1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.colors, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s1.setAdapter(adapter); s1.setOnItemSelectedListener( new OnItemSelectedListener() { public void onItemSelected( AdapterView<?> parent, View view, int position, long id) { showToast("Spinner1: position=" + position + " id=" + id); } public void onNothingSelected(AdapterView<?> parent) { showToast("Spinner1: unselected"); } }); Spinner s2 = (Spinner) findViewById(R.id.spinner2); adapter = ArrayAdapter.createFromResource(this, R.array.planets, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s2.setAdapter(adapter); s2.setOnItemSelectedListener( new OnItemSelectedListener() { public void onItemSelected( AdapterView<?> parent, View view, int position, long id) { showToast("Spinner2: position=" + position + " id=" + id); } public void onNothingSelected(AdapterView<?> parent) { showToast("Spinner2: unselected"); } }); } } //layout/spinner_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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:orientation="vertical" android:padding="10dip" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="spinner_1_color" /> <Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:prompt="spinner_1_color_prompt" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="spinner_1_planet" /> <Spinner android:id="@+id/spinner2" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:prompt="spinner_1_planet_prompt" /> </LinearLayout>
package com.android.example.spinner; import com.android.example.spinner.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; public class SpinnerActivity extends Activity { protected int mPos; protected String mSelection; protected ArrayAdapter<CharSequence> mAdapter; /** * The initial position of the spinner when it is first installed. */ public static final int DEFAULT_POSITION = 2; public static final String PREFERENCES_FILE = "SpinnerPrefs"; public static final String PROPERTY_DELIMITER = "="; /** * The key or label for "position" in the preferences file */ public static final String POSITION_KEY = "Position"; /** * The key or label for "selection" in the preferences file */ public static final String SELECTION_KEY = "Selection"; public static final String POSITION_MARKER = POSITION_KEY + PROPERTY_DELIMITER; public static final String SELECTION_MARKER = SELECTION_KEY + PROPERTY_DELIMITER; @Override public void onCreate(Bundle savedInstanceState) { /** * derived classes that use onCreate() overrides must always call the super constructor */ super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner spinner = (Spinner) findViewById(R.id.Spinner01); /* * Create a backing mLocalAdapter for the Spinner from a list of the * planets. The list is defined by XML in the strings.xml file. */ this.mAdapter = ArrayAdapter.createFromResource(this, R.array.Planets, android.R.layout.simple_spinner_dropdown_item); /* * Attach the mLocalAdapter to the spinner. */ spinner.setAdapter(this.mAdapter); /* * Create a listener that is triggered when Android detects the * user has selected an item in the Spinner. */ OnItemSelectedListener spinnerListener = new myOnItemSelectedListener(this,this.mAdapter); /* * Attach the listener to the Spinner. */ spinner.setOnItemSelectedListener(spinnerListener); } public class myOnItemSelectedListener implements OnItemSelectedListener { ArrayAdapter<CharSequence> mLocalAdapter; Activity mLocalContext; public myOnItemSelectedListener(Activity c, ArrayAdapter<CharSequence> ad) { this.mLocalContext = c; this.mLocalAdapter = ad; } public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) { SpinnerActivity.this.mPos = pos; SpinnerActivity.this.mSelection = parent.getItemAtPosition(pos).toString(); /* * Set the value of the text field in the UI */ TextView resultText = (TextView)findViewById(R.id.SpinnerResult); resultText.setText(SpinnerActivity.this.mSelection); } public void onNothingSelected(AdapterView<?> parent) { // do nothing } } @Override public void onResume() { /* * an override to onResume() must call the super constructor first. */ super.onResume(); /* * Try to read the preferences file. If not found, set the state to the desired initial * values. */ if (!readInstanceState(this)) setInitialState(); /* * Set the spinner to the current state. */ Spinner restoreSpinner = (Spinner)findViewById(R.id.Spinner01); restoreSpinner.setSelection(getSpinnerPosition()); } @Override public void onPause() { /* * an override to onPause() must call the super constructor first. */ super.onPause(); /* * Save the state to the preferences file. If it fails, display a Toast, noting the failure. */ if (!writeInstanceState(this)) { Toast.makeText(this, "Failed to write state!", Toast.LENGTH_LONG).show(); } } /** * Sets the initial state of the spinner when the application is first run. */ public void setInitialState() { this.mPos = DEFAULT_POSITION; } public boolean readInstanceState(Context c) { SharedPreferences p = c.getSharedPreferences(PREFERENCES_FILE, MODE_WORLD_READABLE); /* * Get the position and value of the spinner from the file, or a default value if the * key-value pair does not exist. */ this.mPos = p.getInt(POSITION_KEY, SpinnerActivity.DEFAULT_POSITION); this.mSelection = p.getString(SELECTION_KEY, ""); /* * SharedPreferences doesn't fail if the code tries to get a non-existent key. The * most straightforward way to indicate success is to return the results of a test that * SharedPreferences contained the position key. */ return (p.contains(POSITION_KEY)); } /** * Write the application's current state to a properties repository. * @param c - The Activity's Context * */ public boolean writeInstanceState(Context c) { /* * Get the SharedPreferences object for this application */ SharedPreferences p = c.getSharedPreferences(SpinnerActivity.PREFERENCES_FILE, MODE_WORLD_READABLE); /* * Get the editor for this object. The editor interface abstracts the implementation of * updating the SharedPreferences object. */ SharedPreferences.Editor e = p.edit(); /* * Write the keys and values to the Editor */ e.putInt(POSITION_KEY, this.mPos); e.putString(SELECTION_KEY, this.mSelection); /* * Commit the changes. Return the result of the commit. The commit fails if Android * failed to commit the changes to persistent storage. */ return (e.commit()); } public int getSpinnerPosition() { return this.mPos; } public void setSpinnerPosition(int pos) { this.mPos = pos; } public String getSpinnerSelection() { return this.mSelection; } public void setSpinnerSelection(String selection) { this.mSelection = selection; } } // //res\layout\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" > <!-- Creates a spinner widget called Spinner01, within the Linear Layout The prompt text comes from the string "planet_prompt" in strings.xml --> <Spinner android:id="@+id/Spinner01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:drawSelectorOnTop = "true" android:prompt = "@string/planet_prompt"> </Spinner> <!-- Creates a TextView called SpinnerResult, below the spinner. --> <TextView android:id="@+id/SpinnerResult" android:text="Result" android:layout_height="fill_parent" android:textSize="10pt" android:textStyle="bold" android:gravity="center" android:layout_width="fill_parent"> </TextView> </LinearLayout> // //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Spinner</string> <string-array name="Planets"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> <item>Pluto</item> </string-array> <string name="planet_prompt">Select a planet</string> </resources> // C:\Java_Dev\sdk\Android\android-sdk\samples\android-13\SpinnerTest\src\com\android\example\spinner\test\SpinnerActivityTest.java package com.android.example.spinner.test; import com.android.example.spinner.SpinnerActivity; import android.app.Instrumentation; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.view.KeyEvent; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; public class SpinnerActivityTest extends ActivityInstrumentationTestCase2<SpinnerActivity> { // Number of items in the spinner's backing mLocalAdapter public static final int ADAPTER_COUNT = 9; // The location of Saturn in the backing mLocalAdapter array (0-based) public static final int TEST_POSITION = 5; // Set the initial position of the spinner to zero public static final int INITIAL_POSITION = 0; // The initial position corresponds to Mercury public static final String INITIAL_SELECTION = "Mercury"; // Test values of position and selection for the testStateDestroy test public static final int TEST_STATE_DESTROY_POSITION = 2; public static final String TEST_STATE_DESTROY_SELECTION = "Earth"; // Test values of position and selection for the testStatePause test public static final int TEST_STATE_PAUSE_POSITION = 4; public static final String TEST_STATE_PAUSE_SELECTION = "Jupiter"; // The Application object for the application under test private SpinnerActivity mActivity; // String displayed in the spinner in the app under test private String mSelection; // The currently selected position in the spinner in the app under test private int mPos; /* * The Spinner object in the app under test. Used with instrumentation to control the * app under test. */ private Spinner mSpinner; private SpinnerAdapter mPlanetData; public SpinnerActivityTest() { super("com.android.example.spinner", SpinnerActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); setActivityInitialTouchMode(false); mActivity = getActivity(); mSpinner = (Spinner)mActivity.findViewById(com.android.example.spinner.R.id.Spinner01); mPlanetData = mSpinner.getAdapter(); } public void testPreconditions() { assertTrue(mSpinner.getOnItemSelectedListener() != null); assertTrue(mPlanetData != null); assertEquals(mPlanetData.getCount(), ADAPTER_COUNT); } public void testSpinnerUI() { mActivity.runOnUiThread( new Runnable() { public void run() { mSpinner.requestFocus(); mSpinner.setSelection(INITIAL_POSITION); } } ); this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); for (int i = 1; i <= TEST_POSITION; i++) { this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); } this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); mPos = mSpinner.getSelectedItemPosition(); mSelection = (String)mSpinner.getItemAtPosition(mPos); TextView resultView = (TextView) mActivity.findViewById(com.android.example.spinner.R.id.SpinnerResult); // Get the String value in the EditText object String resultText = (String) resultView.getText(); assertEquals(resultText,mSelection); } public void testStateDestroy() { mActivity.setSpinnerPosition(TEST_STATE_DESTROY_POSITION); mActivity.setSpinnerSelection(TEST_STATE_DESTROY_SELECTION); // Halt the Activity by calling Activity.finish() on it mActivity.finish(); // Restart the activity by calling ActivityInstrumentationTestCase2.getActivity() mActivity = this.getActivity(); int currentPosition = mActivity.getSpinnerPosition(); String currentSelection = mActivity.getSpinnerSelection(); // test that they are the same. assertEquals(TEST_STATE_DESTROY_POSITION, currentPosition); assertEquals(TEST_STATE_DESTROY_SELECTION, currentSelection); } @UiThreadTest public void testStatePause() { Instrumentation instr = this.getInstrumentation(); mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION); mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION); instr.callActivityOnPause(mActivity); mActivity.setSpinnerPosition(0); mActivity.setSpinnerSelection(""); instr.callActivityOnResume(mActivity); int currentPosition = mActivity.getSpinnerPosition(); String currentSelection = mActivity.getSpinnerSelection(); assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition); assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection); } } // C:\Java_Dev\sdk\Android\android-sdk\samples\android-13\SpinnerTest\res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">SpinnerTest</string> </resources>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.Spinner; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner spinner = (Spinner)findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.planets, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } } //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" > <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> //arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="planets"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> </string-array> </resources>
package app.test; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class Test extends Activity { Spinner spinner_c; Spinner spinner_2; private ArrayAdapter<String> aspnCountries; private List<String> allcountries; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("SpinnerActivity"); setContentView(R.layout.main); find_and_modify_view(); } private static final String[] mCountries = { "China" ,"Russia", "Germany", "Ukraine", "Belarus", "USA" }; private void find_and_modify_view() { spinner_c = (Spinner) findViewById(R.id.spinner_1); allcountries = new ArrayList<String>(); for (int i = 0; i < mCountries.length; i++) { allcountries.add(mCountries[i]); } aspnCountries = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, allcountries); aspnCountries .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_c.setAdapter(aspnCountries); spinner_2 = (Spinner) findViewById(R.id.spinner_2); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.countries, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_2.setAdapter(adapter); } } //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="Spinner_1" /> <Spinner android:id="@+id/spinner_1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="false" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Spinner_2 From arrays xml file" /> <Spinner android:id="@+id/spinner_2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="false" /> </LinearLayout> //arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Used in Spinner/spinner_2.java --> <string-array name="countries"> <item>China2</item> <item>Russia2</item> <item>Germany2</item> <item>Ukraine2</item> <item>Belarus2</item> <item>USA2</item> </string-array> </resources>
package app.test; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final Spinner spinner = (Spinner) findViewById(R.id.testSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Months); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); final Button changeButton = (Button) findViewById(R.id.enableButton); changeButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption(spinner); } }); final Button changeButton2 = (Button) findViewById(R.id.backgroundColorButton); changeButton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption2(spinner); } }); } static final String[] Months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public void changeOption(Spinner spinner) { if (spinner.isEnabled()) { spinner.setEnabled(false); } else { spinner.setEnabled(true); } } public void changeOption2(Spinner spinner) { spinner.setBackgroundColor(Color.RED); } } //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" > <Spinner android:id="@+id/testSpinner" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/enableButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Set isEnabled"/> <Button android:id="@+id/backgroundColorButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Background Color"/> </LinearLayout>
package app.test; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final Spinner spinner = (Spinner) findViewById(R.id.testSpinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Months); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); final Button changeButton = (Button) findViewById(R.id.enableButton); changeButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption(spinner); } }); final Button changeButton2 = (Button) findViewById(R.id.backgroundColorButton); changeButton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption2(spinner); } }); } static final String[] Months = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; public void changeOption(Spinner spinner) { if (spinner.isEnabled()) { spinner.setEnabled(false); } else { spinner.setEnabled(true); } } public void changeOption2(Spinner spinner) { spinner.setBackgroundColor(Color.RED); } } //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" > <Spinner android:id="@+id/testSpinner" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/enableButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Set isEnabled"/> <Button android:id="@+id/backgroundColorButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Background Color"/> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; public class Test extends Activity { String[] presidents; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); presidents = getResources().getStringArray(R.array.presidents_array); Spinner s1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, presidents); s1.setAdapter(adapter); s1.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { int index = arg0.getSelectedItemPosition(); Toast.makeText(getBaseContext(), "You have selected item : " + presidents[index], Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); } } //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" > <Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawSelectorOnTop="true" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">BasicViews5</string> <string-array name="presidents_array"> <item>Dwight D. Eisenhower</item> <item>John F. Kennedy</item> <item>Lyndon B. Johnson</item> <item>Richard Nixon</item> <item>Gerald Ford</item> <item>Jimmy Carter</item> <item>Ronald Reagan</item> <item>George H. W. Bush</item> <item>Bill Clinton</item> <item>George W. Bush</item> <item>Barack Obama</item> </string-array> </resources>
4-TabHost
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.TabHost; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); TabHost tabs=(TabHost)findViewById(R.id.tabhost); tabs.setup(); TabHost.TabSpec spec=tabs.newTabSpec("tag1"); spec.setContent(R.id.tab1); spec.setIndicator("Clock"); tabs.addTab(spec); spec=tabs.newTabSpec("tag2"); spec.setContent(R.id.tab2); spec.setIndicator("Button"); tabs.addTab(spec); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"> <AnalogClock android:id="@+id/tab1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerHorizontal="true" /> <Button android:id="@+id/tab2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="A semi-random button" /> </FrameLayout> </LinearLayout> </TabHost>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.TabActivity; import android.os.Bundle; import android.view.View; import android.widget.TabHost; import android.widget.TextView; /** * Uses a right gravity for the TabWidget. */ public class Tabs6 extends TabActivity implements TabHost.TabContentFactory { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabs_right_gravity); final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("tab1", getResources().getDrawable(R.drawable.star_big_on)) .setContent(this)); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("tab2") .setContent(this)); tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("tab3") .setContent(this)); } public View createTabContent(String tag) { final TextView tv = new TextView(this); tv.setText("Content for tab with tag " + tag); return tv; } } //layout/tabs_right_gravity.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. --> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right|center_vertical" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" /> </LinearLayout> </TabHost>
package apt.tutorial; import android.app.TabActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class LunchList extends TabActivity { List<Restaurant> model=new ArrayList<Restaurant>(); RestaurantAdapter adapter=null; EditText name=null; EditText address=null; RadioGroup types=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name=(EditText)findViewById(R.id.name); address=(EditText)findViewById(R.id.addr); types=(RadioGroup)findViewById(R.id.types); Button save=(Button)findViewById(R.id.save); save.setOnClickListener(onSave); ListView list=(ListView)findViewById(R.id.restaurants); adapter=new RestaurantAdapter(); list.setAdapter(adapter); TabHost.TabSpec spec=getTabHost().newTabSpec("tag1"); spec.setContent(R.id.restaurants); spec.setIndicator("List", getResources() .getDrawable(R.drawable.list)); getTabHost().addTab(spec); spec=getTabHost().newTabSpec("tag2"); spec.setContent(R.id.details); spec.setIndicator("Details", getResources() .getDrawable(R.drawable.restaurant)); getTabHost().addTab(spec); getTabHost().setCurrentTab(0); list.setOnItemClickListener(onListClick); } private View.OnClickListener onSave=new View.OnClickListener() { public void onClick(View v) { Restaurant r=new Restaurant(); r.setName(name.getText().toString()); r.setAddress(address.getText().toString()); switch (types.getCheckedRadioButtonId()) { case R.id.sit_down: r.setType("sit_down"); break; case R.id.take_out: r.setType("take_out"); break; case R.id.delivery: r.setType("delivery"); break; } adapter.add(r); } }; private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Restaurant r=model.get(position); name.setText(r.getName()); address.setText(r.getAddress()); if (r.getType().equals("sit_down")) { types.check(R.id.sit_down); } else if (r.getType().equals("take_out")) { types.check(R.id.take_out); } else { types.check(R.id.delivery); } getTabHost().setCurrentTab(1); } }; class RestaurantAdapter extends ArrayAdapter<Restaurant> { RestaurantAdapter() { super(LunchList.this, R.layout.row, model); } public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; RestaurantHolder holder=null; if (row==null) { LayoutInflater inflater=getLayoutInflater(); row=inflater.inflate(R.layout.row, parent, false); holder=new RestaurantHolder(row); row.setTag(holder); } else { holder=(RestaurantHolder)row.getTag(); } holder.populateFrom(model.get(position)); return(row); } } static class RestaurantHolder { private TextView name=null; private TextView address=null; private ImageView icon=null; RestaurantHolder(View row) { name=(TextView)row.findViewById(R.id.title); address=(TextView)row.findViewById(R.id.address); icon=(ImageView)row.findViewById(R.id.icon); } void populateFrom(Restaurant r) { name.setText(r.getName()); address.setText(r.getAddress()); if (r.getType().equals("sit_down")) { icon.setImageResource(R.drawable.ball_red); } else if (r.getType().equals("take_out")) { icon.setImageResource(R.drawable.ball_yellow); } else { icon.setImageResource(R.drawable.ball_green); } } } } package apt.tutorial; public class Restaurant { private String name=""; private String address=""; private String type=""; public String getName() { return(name); } public void setName(String name) { this.name=name; } public String getAddress() { return(address); } public void setAddress(String address) { this.address=address; } public String getType() { return(type); } public void setType(String type) { this.type=type; } public String toString() { return(getName()); } } //row.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="4dip" > <ImageView android:id="@+id/icon" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_marginRight="4dip" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:textStyle="bold" android:singleLine="true" android:ellipsize="end" /> <TextView android:id="@+id/address" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:singleLine="true" android:ellipsize="end" /> </LinearLayout> </LinearLayout> //main.xml <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/restaurants" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <TableLayout android:id="@+id/details" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1" android:paddingTop="4dip" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" /> </TableRow> <TableRow> <TextView android:text="Type:" /> <RadioGroup android:id="@+id/types"> <RadioButton android:id="@+id/take_out" android:text="Take-Out" /> <RadioButton android:id="@+id/sit_down" android:text="Sit-Down" /> <RadioButton android:id="@+id/delivery" android:text="Delivery" /> </RadioGroup> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout> </FrameLayout> </LinearLayout> </TabHost> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LunchList</string> </resources>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AnalogClock; import android.widget.Button; import android.widget.TabHost; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final TabHost tabs=(TabHost)findViewById(R.id.tabhost); tabs.setup(); TabHost.TabSpec spec=tabs.newTabSpec("buttontab"); spec.setContent(R.id.buttontab); spec.setIndicator("Button"); tabs.addTab(spec); Button btn=(Button)tabs.getCurrentView().findViewById(R.id.buttontab); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { TabHost.TabSpec spec=tabs.newTabSpec("tag1"); spec.setContent(new TabHost.TabContentFactory() { public View createTabContent(String tag) { return(new AnalogClock(Test.this)); } }); spec.setIndicator("Clock"); tabs.addTab(spec); } }); } } //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"> <TabHost android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingTop="62px"> <Button android:id="@+id/buttontab" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="A semi-random button" /> </FrameLayout> </TabHost> </LinearLayout>
package com.example.android.apis.view; import android.app.TabActivity; import android.os.Bundle; import android.widget.TabHost; import android.content.Intent; /** * An example of tab content that launches an activity via {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)} */ public class Tabs3 extends TabActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("list") .setContent(new Intent(this, List1.class))); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("photo list") .setContent(new Intent(this, List8.class))); // This tab sets the intent flag so that it is recreated each time // the tab is clicked. tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("destroy") .setContent(new Intent(this, Controls1.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))); } }
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.TabActivity; import android.os.Bundle; import android.view.View; import android.widget.TabHost; import android.widget.TextView; /** * Example of using a tab content factory for the content via {@link TabHost.TabSpec#setContent(android.widget.TabHost.TabContentFactory)} * * It also demonstrates using an icon on one of the tabs via {@link TabHost.TabSpec#setIndicator(CharSequence, android.graphics.drawable.Drawable)} * */ public class Tabs2 extends TabActivity implements TabHost.TabContentFactory { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final TabHost tabHost = getTabHost(); tabHost.addTab(tabHost.newTabSpec("tab1") .setIndicator("tab1", getResources().getDrawable(R.drawable.star_big_on)) .setContent(this)); tabHost.addTab(tabHost.newTabSpec("tab2") .setIndicator("tab2") .setContent(this)); tabHost.addTab(tabHost.newTabSpec("tab3") .setIndicator("tab3") .setContent(this)); } /** {@inheritDoc} */ public View createTabContent(String tag) { final TextView tv = new TextView(this); tv.setText("Content for tab with tag " + tag); return tv; } }
package app.test; import android.app.TabActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.TabHost; public class Test extends TabActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("TabDemoActivity"); TabHost tabHost = getTabHost(); LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true); tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1") .setContent(R.id.view1)); tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab2") .setContent(R.id.view2)); tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3") .setContent(R.id.view3)); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/view1" android:background="@drawable/icon" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Tab1"/> <TextView android:id="@+id/view2" android:background="@drawable/icon" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Tab2"/> <TextView android:id="@+id/view3" android:background="@drawable/icon" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Tab3"/> </FrameLayout>
5-TimePicker
package app.test; import android.app.Activity; import android.os.Bundle; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TimePicker; import android.widget.TextView; import java.text.DateFormat; import java.util.Calendar; public class Test extends Activity { DateFormat fmtDateAndTime=DateFormat.getDateTimeInstance(); TextView dateAndTimeLabel; Calendar dateAndTime=Calendar.getInstance(); DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { dateAndTime.set(Calendar.YEAR, year); dateAndTime.set(Calendar.MONTH, monthOfYear); dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth); updateLabel(); } }; TimePickerDialog.OnTimeSetListener t=new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { dateAndTime.set(Calendar.HOUR_OF_DAY, hourOfDay); dateAndTime.set(Calendar.MINUTE, minute); updateLabel(); } }; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Button btn=(Button)findViewById(R.id.dateBtn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new DatePickerDialog(Test.this, d, dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH)).show(); } }); btn=(Button)findViewById(R.id.timeBtn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new TimePickerDialog(Test.this, t, dateAndTime.get(Calendar.HOUR_OF_DAY), dateAndTime.get(Calendar.MINUTE), true).show(); } }); dateAndTimeLabel=(TextView)findViewById(R.id.dateAndTime); updateLabel(); } private void updateLabel() { dateAndTimeLabel.setText(fmtDateAndTime.format(dateAndTime.getTime())); } } //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:id="@+id/dateAndTime" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/dateBtn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Set the Date" /> <Button android:id="@+id/timeBtn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Set the Time" /> </LinearLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.widget.TextView; import android.widget.TimePicker; import android.os.Bundle; public class DateWidgets2 extends Activity { // where we display the selected date and time private TextView mTimeDisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker); timePicker.setCurrentHour(12); timePicker.setCurrentMinute(15); mTimeDisplay = (TextView) findViewById(R.id.dateDisplay); updateDisplay(12, 15); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { updateDisplay(hourOfDay, minute); } }); } private void updateDisplay(int hourOfDay, int minute) { mTimeDisplay.setText( new StringBuilder() .append(pad(hourOfDay)).append(":") .append(pad(minute))); } private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- example of using the time changed callback, with now visible 'set' button--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TimePicker android:id="@+id/timePicker" android:layout_height="wrap_content" android:layout_width="match_parent"/> <TextView android:id="@+id/dateDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="4dip" android:text="date_widgets_example_dateDisplay_text"/> </LinearLayout>
Basic example of using date and time widgets, android.app.TimePickerDialog android.widget.DatePicker.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.app.Dialog; import android.os.Bundle; import android.widget.TextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.TimePicker; import android.view.View; import java.util.Calendar; /** * Basic example of using date and time widgets, including * {@link android.app.TimePickerDialog} and {@link android.widget.DatePicker}. * * Also provides a good example of using {@link Activity#onCreateDialog}, * {@link Activity#onPrepareDialog} and {@link Activity#showDialog} to have the * activity automatically save and restore the state of the dialogs. */ public class DateWidgets1 extends Activity { // where we display the selected date and time private TextView mDateDisplay; // date and time private int mYear; private int mMonth; private int mDay; private int mHour; private int mMinute; static final int TIME_DIALOG_ID = 0; static final int DATE_DIALOG_ID = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDateDisplay = (TextView) findViewById(R.id.dateDisplay); Button pickDate = (Button) findViewById(R.id.pickDate); pickDate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); Button pickTime = (Button) findViewById(R.id.pickTime); pickTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(TIME_DIALOG_ID); } }); final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); updateDisplay(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case TIME_DIALOG_ID: return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false); case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case TIME_DIALOG_ID: ((TimePickerDialog) dialog).updateTime(mHour, mMinute); break; case DATE_DIALOG_ID: ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay); break; } } private void updateDisplay() { mDateDisplay.setText( new StringBuilder() // Month is 0 based so add 1 .append(mMonth + 1).append("-") .append(mDay).append("-") .append(mYear).append(" ") .append(pad(mHour)).append(":") .append(pad(mMinute))); } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay(); } }; private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mHour = hourOfDay; mMinute = minute; updateDisplay(); } }; private static String pad(int c) { if (c >= 10) return String.valueOf(c); else return "0" + String.valueOf(c); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/dateDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="date_widgets_example_dateDisplay_text"/> </LinearLayout> <Button android:id="@+id/pickDate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="date_widgets_example_pickDate_text"/> <Button android:id="@+id/pickTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="date_widgets_example_pickTime_text"/> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView dateDefault = (TextView)findViewById(R.id.dateDefault); TextView timeDefault = (TextView)findViewById(R.id.timeDefault); DatePicker dp = (DatePicker)this.findViewById(R.id.datePicker); dateDefault.setText("Date defaulted to " + (dp.getMonth() + 1) + "/" + dp.getDayOfMonth() + "/" + dp.getYear()); dp.init(2008, 11, 10, null); TimePicker tp = (TimePicker)this.findViewById(R.id.timePicker); java.util.Formatter timeF = new java.util.Formatter(); timeF.format("Time defaulted to %d:%02d", tp.getCurrentHour(), tp.getCurrentMinute()); timeDefault.setText(timeF.toString()); tp.setIs24HourView(true); tp.setCurrentHour(new Integer(10)); tp.setCurrentMinute(new Integer(10)); } } //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:id="@+id/dateDefault" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/timeDefault" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <DigitalClock android:layout_width="wrap_content" android:layout_height="wrap_content" /> <AnalogClock android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.TimePicker; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("TimePickerActivity"); setContentView(R.layout.main); TimePicker tp = (TimePicker) this.findViewById(R.id.time_picker); tp.setIs24HourView(true); } } //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="wrap_content"> <TimePicker android:id="@+id/time_picker" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
package app.test; import java.util.Calendar; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.TimePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TimePicker; import android.widget.Toast; public class Test extends Activity { TimePicker timePicker; DatePicker datePicker; int hour, minute; int yr, month, day; static final int TIME_DIALOG_ID = 0; static final int DATE_DIALOG_ID = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Calendar today = Calendar.getInstance(); yr = today.get(Calendar.YEAR); month = today.get(Calendar.MONTH); day = today.get(Calendar.DAY_OF_MONTH); showDialog(DATE_DIALOG_ID); timePicker = (TimePicker) findViewById(R.id.timePicker); timePicker.setIs24HourView(true); datePicker = (DatePicker) findViewById(R.id.datePicker); Button btnOpen = (Button) findViewById(R.id.btnSet); btnOpen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText( getBaseContext(), "Date selected:" + datePicker.getMonth() + 1 + "/" + datePicker.getDayOfMonth() + "/" + datePicker.getYear() + "\n" + "Time selected:" + timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute(), Toast.LENGTH_SHORT).show(); } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case TIME_DIALOG_ID: return new TimePickerDialog(this, mTimeSetListener, hour, minute, false); case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, yr, month, day); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { yr = year; month = monthOfYear; day = dayOfMonth; Toast.makeText( getBaseContext(), "You have selected : " + (month + 1) + "/" + day + "/" + year, Toast.LENGTH_SHORT).show(); } }; private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minuteOfHour) { hour = hourOfDay; minute = minuteOfHour; Toast.makeText(getBaseContext(), "You have selected : " + hour + ":" + minute, Toast.LENGTH_SHORT).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" > <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btnSet" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am all set!" /> </LinearLayout>
6-Gallery
package app.test; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.content.res.TypedArray; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; public class Test extends Activity { //---the images to display--- Integer[] imageIDs = { R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery gallery = (Gallery) findViewById(R.id.gallery1); gallery.setAdapter(new ImageAdapter(this)); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(getBaseContext(), "pic" + (position + 1) + " selected", Toast.LENGTH_SHORT).show(); ImageView imageView = (ImageView) findViewById(R.id.image1); imageView.setImageResource(imageIDs[position]); } }); } public class ImageAdapter extends BaseAdapter { private Context context; private int itemBackground; public ImageAdapter(Context c) { context = c; //---setting the style--- TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); itemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); } //---returns the number of images--- public int getCount() { return imageIDs.length; } //---returns the ID of an item--- public Object getItem(int position) { return position; } //---returns the ID of an item--- public long getItemId(int position) { return position; } //---returns an ImageView view--- public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(context); imageView.setImageResource(imageIDs[position]); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setLayoutParams(new Gallery.LayoutParams(150, 120)); imageView.setBackgroundResource(itemBackground); return imageView; } } } //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="Images of San Francisco" /> <Gallery android:id="@+id/gallery1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image1" android:layout_width="320px" android:layout_height="250px" android:scaleType="fitXY" /> </LinearLayout>
import android.content.Context; import android.graphics.Camera; import android.graphics.Matrix; import android.util.AttributeSet; import android.view.View; import android.view.animation.Transformation; import android.widget.Gallery; import android.widget.ImageView; public class CoverFlow extends Gallery { /** * Graphics Camera used for transforming the matrix of ImageViews */ private Camera mCamera = new Camera(); /** * The maximum angle the Child ImageView will be rotated by */ private int mMaxRotationAngle = 70; /** * The maximum zoom on the centre Child */ private int mMaxZoom = -180; /** * The Centre of the Coverflow */ private int mCoveflowCenter; public CoverFlow(Context context) { super(context); this.setStaticTransformationsEnabled(true); } public CoverFlow(Context context, AttributeSet attrs) { super(context, attrs); this.setStaticTransformationsEnabled(true); } public CoverFlow(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.setStaticTransformationsEnabled(true); } /** * Get the max rotational angle of the image * * @return the mMaxRotationAngle */ public int getMaxRotationAngle() { return mMaxRotationAngle; } /** * Set the max rotational angle of each image * * @param maxRotationAngle * the mMaxRotationAngle to set */ public void setMaxRotationAngle(int maxRotationAngle) { mMaxRotationAngle = maxRotationAngle; } /** * Get the Max zoom of the centre image * * @return the mMaxZoom */ public int getMaxZoom() { return mMaxZoom; } /** * Set the max zoom of the centre image * * @param maxZoom * the mMaxZoom to set */ public void setMaxZoom(int maxZoom) { mMaxZoom = maxZoom; } /** * Get the Centre of the Coverflow * * @return The centre of this Coverflow. */ private int getCenterOfCoverflow() { return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2 + getPaddingLeft(); } /** * Get the Centre of the View * * @return The centre of the given view. */ private static int getCenterOfView(View view) { return view.getLeft() + view.getWidth() / 2; } /** * {@inheritDoc} * * @see #setStaticTransformationsEnabled(boolean) */ protected boolean getChildStaticTransformation(View child, Transformation t) { final int childCenter = getCenterOfView(child); final int childWidth = child.getWidth(); int rotationAngle = 0; t.clear(); t.setTransformationType(Transformation.TYPE_MATRIX); if (childCenter == mCoveflowCenter) { transformImageBitmap((ImageView) child, t, 0); } else { rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle); if (Math.abs(rotationAngle) > mMaxRotationAngle) { rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle : mMaxRotationAngle; } transformImageBitmap((ImageView) child, t, rotationAngle); } return true; } /** * This is called during layout when the size of this view has changed. If * you were just added to the view hierarchy, you're called with the old * values of 0. * * @param w * Current width of this view. * @param h * Current height of this view. * @param oldw * Old width of this view. * @param oldh * Old height of this view. */ protected void onSizeChanged(int w, int h, int oldw, int oldh) { mCoveflowCenter = getCenterOfCoverflow(); super.onSizeChanged(w, h, oldw, oldh); } /** * Transform the Image Bitmap by the Angle passed * * @param imageView * ImageView the ImageView whose bitmap we want to rotate * @param t * transformation * @param rotationAngle * the Angle by which to rotate the Bitmap */ private void transformImageBitmap(ImageView child, Transformation t, int rotationAngle) { mCamera.save(); final Matrix imageMatrix = t.getMatrix(); ; final int imageHeight = child.getLayoutParams().height; ; final int imageWidth = child.getLayoutParams().width; final int rotation = Math.abs(rotationAngle); mCamera.translate(0.0f, 0.0f, 100.0f); // As the angle of the view gets less, zoom in if (rotation < mMaxRotationAngle) { float zoomAmount = (float) (mMaxZoom + (rotation * 1.5)); mCamera.translate(0.0f, 0.0f, zoomAmount); } mCamera.rotateY(rotationAngle); mCamera.getMatrix(imageMatrix); imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2)); imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2)); mCamera.restore(); } }
import android.app.Activity; import android.content.SharedPreferences; final class SharedUtils { private static final String SHARED_NAME = "SETTINGS"; private static final String GALLERY_SHOW_MODE = "GALLERY_SHOW_MODE"; public static boolean getGalleryShowMode(final Activity activity) { final SharedPreferences settings = activity.getSharedPreferences(SHARED_NAME, 0); return settings.getBoolean(GALLERY_SHOW_MODE, true); } public static void putGalleryShowMode(final Activity activity, final boolean value) { final SharedPreferences settings = activity.getSharedPreferences(SHARED_NAME, 0); final SharedPreferences.Editor edit = settings.edit(); edit.putBoolean(GALLERY_SHOW_MODE, value); edit.commit(); } }
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class Gallery1 extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gallery_1); // Reference the Gallery view Gallery g = (Gallery) findViewById(R.id.gallery); // Set the adapter to our custom adapter (below) g.setAdapter(new ImageAdapter(this)); // Set a item click listener, and just Toast the clicked position g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show(); } }); // We also want to show context menu for longpressed items in the gallery registerForContextMenu(g); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(R.string.gallery_2_text); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Toast.makeText(this, "Longpress: " + info.position, Toast.LENGTH_SHORT).show(); return true; } public class ImageAdapter extends BaseAdapter { private static final int ITEM_WIDTH = 136; private static final int ITEM_HEIGHT = 88; private final int mGalleryItemBackground; private final Context mContext; private final Integer[] mImageIds = { R.drawable.gallery_photo_1, R.drawable.gallery_photo_2, R.drawable.gallery_photo_3, R.drawable.gallery_photo_4, R.drawable.gallery_photo_5, R.drawable.gallery_photo_6, R.drawable.gallery_photo_7, R.drawable.gallery_photo_8 }; private final float mDensity; public ImageAdapter(Context c) { mContext = c; // See res/values/attrs.xml for the <declare-styleable> that defines // Gallery1. TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); mDensity = c.getResources().getDisplayMetrics().density; } public int getCount() { return mImageIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { convertView = new ImageView(mContext); imageView = (ImageView) convertView; imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setLayoutParams(new Gallery.LayoutParams( (int) (ITEM_WIDTH * mDensity + 0.5f), (int) (ITEM_HEIGHT * mDensity + 0.5f))); // The preferred Gallery item background imageView.setBackgroundResource(mGalleryItemBackground); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mImageIds[position]); return imageView; } } } //layout/gallery_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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:id="@+id/layout2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Gallery android:id="@+id/gallery" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_width="wrap_content" android:layout_height="wrap_content"></EditText> </LinearLayout>
package com.example.android.hcgallery; import java.io.IOException; import java.util.List; import android.app.Fragment; import android.app.Activity; import android.app.ActionBar; import android.content.Context; import android.content.Intent; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Size; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; public class CameraFragment extends Fragment { private Preview mPreview; Camera mCamera; int mNumberOfCameras; int mCameraCurrentlyLocked; // The first rear facing camera int mDefaultCameraId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a RelativeLayout container that will hold a SurfaceView, // and set it as the content of our activity. mPreview = new Preview(this.getActivity()); // Find the total number of cameras available mNumberOfCameras = Camera.getNumberOfCameras(); // Find the ID of the default camera CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < mNumberOfCameras; i++) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { mDefaultCameraId = i; } } setHasOptionsMenu(mNumberOfCameras > 1); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Add an up arrow to the "home" button, indicating that the button will go "up" // one activity in the app's Activity heirarchy. // Calls to getActionBar() aren't guaranteed to return the ActionBar when called // from within the Fragment's onCreate method, because the Window's decor hasn't been // initialized yet. Either call for the ActionBar reference in Activity.onCreate() // (after the setContentView(...) call), or in the Fragment's onActivityCreated method. Activity activity = this.getActivity(); ActionBar actionBar = activity.getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return mPreview; } @Override public void onResume() { super.onResume(); // Open the default i.e. the first rear facing camera. mCamera = Camera.open(mDefaultCameraId); mCameraCurrentlyLocked = mDefaultCameraId; mPreview.setCamera(mCamera); } @Override public void onPause() { super.onPause(); // Because the Camera object is a shared resource, it's very // important to release it when the activity is paused. if (mCamera != null) { mPreview.setCamera(null); mCamera.release(); mCamera = null; } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (mNumberOfCameras > 1) { // Inflate our menu which can gather user input for switching camera inflater.inflate(R.menu.camera_menu, menu); } else { super.onCreateOptionsMenu(menu, inflater); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.switch_cam: // Release this camera -> mCameraCurrentlyLocked if (mCamera != null) { mCamera.stopPreview(); mPreview.setCamera(null); mCamera.release(); mCamera = null; } // Acquire the next camera and request Preview to reconfigure // parameters. mCamera = Camera .open((mCameraCurrentlyLocked + 1) % mNumberOfCameras); mCameraCurrentlyLocked = (mCameraCurrentlyLocked + 1) % mNumberOfCameras; mPreview.switchCamera(mCamera); // Start the preview mCamera.startPreview(); return true; case android.R.id.home: Intent intent = new Intent(this.getActivity(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); default: return super.onOptionsItemSelected(item); } } } // ---------------------------------------------------------------------- /** * A simple wrapper around a Camera and a SurfaceView that renders a centered * preview of the Camera to the surface. We need to center the SurfaceView * because not all devices have cameras that support preview sizes at the same * aspect ratio as the device's display. */ class Preview extends ViewGroup implements SurfaceHolder.Callback { private final String TAG = "Preview"; SurfaceView mSurfaceView; SurfaceHolder mHolder; Size mPreviewSize; List<Size> mSupportedPreviewSizes; Camera mCamera; Preview(Context context) { super(context); mSurfaceView = new SurfaceView(context); addView(mSurfaceView); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = mSurfaceView.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void setCamera(Camera camera) { mCamera = camera; if (mCamera != null) { mSupportedPreviewSizes = mCamera.getParameters() .getSupportedPreviewSizes(); requestLayout(); } } public void switchCamera(Camera camera) { setCamera(camera); try { camera.setPreviewDisplay(mHolder); } catch (IOException exception) { Log.e(TAG, "IOException caused by setPreviewDisplay()", exception); } Camera.Parameters parameters = camera.getParameters(); parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); requestLayout(); camera.setParameters(parameters); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // We purposely disregard child measurements because act as a // wrapper to a SurfaceView that centers the camera preview instead // of stretching it. final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); if (mSupportedPreviewSizes != null) { mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (changed && getChildCount() > 0) { final View child = getChildAt(0); final int width = r - l; final int height = b - t; int previewWidth = width; int previewHeight = height; if (mPreviewSize != null) { previewWidth = mPreviewSize.width; previewHeight = mPreviewSize.height; } // Center the child SurfaceView within the parent. if (width * previewHeight > height * previewWidth) { final int scaledChildWidth = previewWidth * height / previewHeight; child.layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height); } else { final int scaledChildHeight = previewHeight * width / previewWidth; child.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2); } } } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. try { if (mCamera != null) { mCamera.setPreviewDisplay(holder); } } catch (IOException exception) { Log.e(TAG, "IOException caused by setPreviewDisplay()", exception); } } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. if (mCamera != null) { mCamera.stopPreview(); } } private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.1; double targetRatio = (double) w / h; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height); requestLayout(); mCamera.setParameters(parameters); mCamera.startPreview(); } } //src\com\example\android\hcgallery\CameraSample.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.app.Activity; import android.os.Bundle; public class CameraSample extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { int themeId = this.getIntent().getExtras().getInt("theme"); this.setTheme(themeId); super.onCreate(savedInstanceState); setContentView(R.layout.camera_sample); } } //src\com\example\android\hcgallery\ContentFragment.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.content.ClipData; import android.content.ClipData.Item; import android.content.ClipDescription; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.ActionMode; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.StringTokenizer; public class ContentFragment extends Fragment { private View mContentView; // The bitmap currently used by ImageView private Bitmap mBitmap = null; // Current action mode (contextual action bar, a.k.a. CAB) private ActionMode mCurrentActionMode; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mContentView = inflater.inflate(R.layout.content_welcome, null); final ImageView imageView = (ImageView) mContentView.findViewById(R.id.image); mContentView.setDrawingCacheEnabled(false); mContentView.setOnDragListener(new View.OnDragListener() { public boolean onDrag(View v, DragEvent event) { switch (event.getAction()) { case DragEvent.ACTION_DRAG_ENTERED: mContentView.setBackgroundColor( getResources().getColor(R.color.drag_active_color)); break; case DragEvent.ACTION_DRAG_EXITED: mContentView.setBackgroundColor(Color.TRANSPARENT); break; case DragEvent.ACTION_DRAG_STARTED: return processDragStarted(event); case DragEvent.ACTION_DROP: mContentView.setBackgroundColor(Color.TRANSPARENT); return processDrop(event, imageView); } return false; } }); // Keep the action bar visibility in sync with the system status bar. That is, when entering // 'lights out mode,' hide the action bar, and when exiting this mode, show the action bar. final Activity activity = getActivity(); mContentView.setOnSystemUiVisibilityChangeListener( new View.OnSystemUiVisibilityChangeListener() { public void onSystemUiVisibilityChange(int visibility) { ActionBar actionBar = activity.getActionBar(); if (actionBar != null) { mContentView.setSystemUiVisibility(visibility); if (visibility == View.STATUS_BAR_VISIBLE) { actionBar.show(); } else { actionBar.hide(); } } } }); // Show/hide the system status bar when single-clicking a photo. This is also called // 'lights out mode.' Activating and deactivating this mode also invokes the listener // defined above, which will show or hide the action bar accordingly. mContentView.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mContentView.getSystemUiVisibility() == View.STATUS_BAR_VISIBLE) { mContentView.setSystemUiVisibility(View.STATUS_BAR_HIDDEN); } else { mContentView.setSystemUiVisibility(View.STATUS_BAR_VISIBLE); } } }); // When long-pressing a photo, activate the action mode for selection, showing the // contextual action bar (CAB). mContentView.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View view) { if (mCurrentActionMode != null) { return false; } mCurrentActionMode = getActivity().startActionMode( mContentSelectionActionModeCallback); mContentView.setSelected(true); return true; } }); return mContentView; } boolean processDragStarted(DragEvent event) { // Determine whether to continue processing drag and drop based on the // plain text mime type. ClipDescription clipDesc = event.getClipDescription(); if (clipDesc != null) { return clipDesc.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); } return false; } boolean processDrop(DragEvent event, ImageView imageView) { // Attempt to parse clip data with expected format: category||entry_id. // Ignore event if data does not conform to this format. ClipData data = event.getClipData(); if (data != null) { if (data.getItemCount() > 0) { Item item = data.getItemAt(0); String textData = (String) item.getText(); if (textData != null) { StringTokenizer tokenizer = new StringTokenizer(textData, "||"); if (tokenizer.countTokens() != 2) { return false; } int category = -1; int entryId = -1; try { category = Integer.parseInt(tokenizer.nextToken()); entryId = Integer.parseInt(tokenizer.nextToken()); } catch (NumberFormatException exception) { return false; } updateContentAndRecycleBitmap(category, entryId); // Update list fragment with selected entry. TitlesFragment titlesFrag = (TitlesFragment) getFragmentManager().findFragmentById(R.id.frag_title); titlesFrag.selectPosition(entryId); return true; } } } return false; } void updateContentAndRecycleBitmap(int category, int position) { if (mCurrentActionMode != null) { mCurrentActionMode.finish(); } if (mBitmap != null) { // This is an advanced call and should be used if you // are working with a lot of bitmaps. The bitmap is dead // after this call. mBitmap.recycle(); } // Get the bitmap that needs to be drawn and update the ImageView mBitmap = Directory.getCategory(category).getEntry(position) .getBitmap(getResources()); ((ImageView) getView().findViewById(R.id.image)).setImageBitmap(mBitmap); } void shareCurrentPhoto() { File externalCacheDir = getActivity().getExternalCacheDir(); if (externalCacheDir == null) { Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT).show(); return; } // Prevent media scanning of the cache directory. final File noMediaFile = new File(externalCacheDir, ".nomedia"); try { noMediaFile.createNewFile(); } catch (IOException e) { } // Write the bitmap to temporary storage in the external storage directory (e.g. SD card). // We perform the actual disk write operations on a separate thread using the // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread. final File tempFile = new File(externalCacheDir, "tempfile.jpg"); new AsyncTask<Void, Void, Boolean>() { /** * Compress and write the bitmap to disk on a separate thread. * @return TRUE if the write was successful, FALSE otherwise. */ protected Boolean doInBackground(Void... voids) { try { FileOutputStream fo = new FileOutputStream(tempFile, false); if (!mBitmap.compress(Bitmap.CompressFormat.JPEG, 60, fo)) { Toast.makeText(getActivity(), "Error writing bitmap data.", Toast.LENGTH_SHORT).show(); return Boolean.FALSE; } return Boolean.TRUE; } catch (FileNotFoundException e) { Toast.makeText(getActivity(), "Error writing to USB/external storage.", Toast.LENGTH_SHORT).show(); return Boolean.FALSE; } } /** * After doInBackground completes (either successfully or in failure), we invoke an * intent to share the photo. This code is run on the main (UI) thread. */ protected void onPostExecute(Boolean result) { if (result != Boolean.TRUE) { return; } Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile)); shareIntent.setType("image/jpeg"); startActivity(Intent.createChooser(shareIntent, "Share photo")); } }.execute(); } /** * The callback for the 'photo selected' {@link ActionMode}. In this action mode, we can * provide contextual actions for the selected photo. We currently only provide the 'share' * action, but we could also add clipboard functions such as cut/copy/paste here as well. */ private ActionMode.Callback mContentSelectionActionModeCallback = new ActionMode.Callback() { public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { actionMode.setTitle(R.string.photo_selection_cab_title); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.photo_context_menu, menu); return true; } public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.share: shareCurrentPhoto(); actionMode.finish(); return true; } return false; } public void onDestroyActionMode(ActionMode actionMode) { mContentView.setSelected(false); mCurrentActionMode = null; } }; } //src\com\example\android\hcgallery\Directory.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; public class Directory { private static DirectoryCategory[] mCategories; public static void initializeDirectory() { mCategories = new DirectoryCategory[] { new DirectoryCategory("Balloons", new DirectoryEntry[] { new DirectoryEntry("Red Balloon", R.drawable.red_balloon), new DirectoryEntry("Green Balloon", R.drawable.green_balloon), new DirectoryEntry("Blue Balloon", R.drawable.blue_balloon)}), new DirectoryCategory("Bikes", new DirectoryEntry[] { new DirectoryEntry("Old school huffy", R.drawable.blue_bike), new DirectoryEntry("New Bikes", R.drawable.rainbow_bike), new DirectoryEntry("Chrome Fast", R.drawable.chrome_wheel)}), new DirectoryCategory("Androids", new DirectoryEntry[] { new DirectoryEntry("Steampunk Android", R.drawable.punk_droid), new DirectoryEntry("Stargazing Android", R.drawable.stargazer_droid), new DirectoryEntry("Big Android", R.drawable.big_droid) }), new DirectoryCategory("Pastries", new DirectoryEntry[] { new DirectoryEntry("Cupcake", R.drawable.cupcake), new DirectoryEntry("Donut", R.drawable.donut), new DirectoryEntry("Eclair", R.drawable.eclair), new DirectoryEntry("Froyo", R.drawable.froyo), }), }; } public static int getCategoryCount() { return mCategories.length; } public static DirectoryCategory getCategory(int i) { return mCategories[i]; } } //src\com\example\android\hcgallery\DirectoryCategory.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; public class DirectoryCategory { private String name; private DirectoryEntry[] entries; public DirectoryCategory(String name, DirectoryEntry[] entries) { this.name = name; this.entries = entries; } public String getName() { return name; } public int getEntryCount() { return entries.length; } public DirectoryEntry getEntry(int i) { return entries[i]; } } //src\com\example\android\hcgallery\DirectoryEntry.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; public class DirectoryEntry { private String name; private int resID; public DirectoryEntry(String name, int resID) { this.name = name; this.resID = resID; } public String getName() { return name; } public Drawable getDrawable(Resources res) { return res.getDrawable(resID); } public Bitmap getBitmap(Resources res) { return BitmapFactory.decodeResource(res, resID); } } //src\com\example\android\hcgallery\FitCenterFrameLayout.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * A simple layout that fits and centers each child view, maintaining aspect ratio. */ public class FitCenterFrameLayout extends ViewGroup { public FitCenterFrameLayout(Context context) { super(context); } public FitCenterFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // We purposely disregard child measurements. final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec); setMeasuredDimension(width, height); int childWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.UNSPECIFIED); int childHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED); int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).measure(childWidthSpec, childHeightSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int childCount = getChildCount(); final int parentLeft = getPaddingLeft(); final int parentTop = getPaddingTop(); final int parentRight = r - l - getPaddingRight(); final int parentBottom = b - t - getPaddingBottom(); final int parentWidth = parentRight - parentLeft; final int parentHeight = parentBottom - parentTop; int unpaddedWidth, unpaddedHeight, parentUnpaddedWidth, parentUnpaddedHeight; int childPaddingLeft, childPaddingTop, childPaddingRight, childPaddingBottom; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } // Fit and center the child within the parent. Make sure not to consider padding // as part of the child's aspect ratio. childPaddingLeft = child.getPaddingLeft(); childPaddingTop = child.getPaddingTop(); childPaddingRight = child.getPaddingRight(); childPaddingBottom = child.getPaddingBottom(); unpaddedWidth = child.getMeasuredWidth() - childPaddingLeft - childPaddingRight; unpaddedHeight = child.getMeasuredHeight() - childPaddingTop - childPaddingBottom; parentUnpaddedWidth = parentWidth - childPaddingLeft - childPaddingRight; parentUnpaddedHeight = parentHeight - childPaddingTop - childPaddingBottom; if (parentUnpaddedWidth * unpaddedHeight > parentUnpaddedHeight * unpaddedWidth) { // The child view should be left/right letterboxed. final int scaledChildWidth = unpaddedWidth * parentUnpaddedHeight / unpaddedHeight + childPaddingLeft + childPaddingRight; child.layout( parentLeft + (parentWidth - scaledChildWidth) / 2, parentTop, parentRight - (parentWidth - scaledChildWidth) / 2, parentBottom); } else { // The child view should be top/bottom letterboxed. final int scaledChildHeight = unpaddedHeight * parentUnpaddedWidth / unpaddedWidth + childPaddingTop + childPaddingBottom; child.layout( parentLeft, parentTop + (parentHeight - scaledChildHeight) / 2, parentRight, parentTop + (parentHeight + scaledChildHeight) / 2); } } } } //src\com\example\android\hcgallery\MainActivity.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.app.ActionBar; 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.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.RemoteViews; public class MainActivity extends Activity implements ActionBar.TabListener { private static final int NOTIFICATION_DEFAULT = 1; private static final String ACTION_DIALOG = "com.example.android.hcgallery.action.DIALOG"; private View mActionBarView; private Animator mCurrentTitlesAnimator; private String[] mToggleLabels = {"Show Titles", "Hide Titles"}; private int mLabelIndex = 1; private int mThemeId = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null && savedInstanceState.getInt("theme", -1) != -1) { mThemeId = savedInstanceState.getInt("theme"); this.setTheme(mThemeId); } setContentView(R.layout.main); Directory.initializeDirectory(); ActionBar bar = getActionBar(); int i; for (i = 0; i < Directory.getCategoryCount(); i++) { bar.addTab(bar.newTab().setText(Directory.getCategory(i).getName()) .setTabListener(this)); } mActionBarView = getLayoutInflater().inflate( R.layout.action_bar_custom, null); bar.setCustomView(mActionBarView); bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); bar.setDisplayShowHomeEnabled(true); // If category is not saved to the savedInstanceState, // 0 is returned by default. if(savedInstanceState != null) { int category = savedInstanceState.getInt("category"); bar.selectTab(bar.getTabAt(category)); } } public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { TitlesFragment titleFrag = (TitlesFragment) getFragmentManager() .findFragmentById(R.id.frag_title); titleFrag.populateTitles(tab.getPosition()); titleFrag.selectPosition(0); } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.camera: Intent intent = new Intent(this, CameraSample.class); intent.putExtra("theme", mThemeId); startActivity(intent); return true; case R.id.toggleTitles: toggleVisibleTitles(); return true; case R.id.toggleTheme: if (mThemeId == R.style.AppTheme_Dark) { mThemeId = R.style.AppTheme_Light; } else { mThemeId = R.style.AppTheme_Dark; } this.recreate(); return true; case R.id.showDialog: showDialog("This is indeed an awesome dialog."); return true; case R.id.showStandardNotification: showNotification(false); return true; case R.id.showCustomNotification: showNotification(true); return true; default: return super.onOptionsItemSelected(item); } } public void toggleVisibleTitles() { // Use these for custom animations. final FragmentManager fm = getFragmentManager(); final TitlesFragment f = (TitlesFragment) fm .findFragmentById(R.id.frag_title); final View titlesView = f.getView(); mLabelIndex = 1 - mLabelIndex; // Determine if we're in portrait, and whether we're showing or hiding the titles // with this toggle. final boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; final boolean shouldShow = f.isHidden() || mCurrentTitlesAnimator != null; // Cancel the current titles animation if there is one. if (mCurrentTitlesAnimator != null) mCurrentTitlesAnimator.cancel(); // Begin setting up the object animator. We'll animate the bottom or right edge of the // titles view, as well as its alpha for a fade effect. ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder( titlesView, PropertyValuesHolder.ofInt( isPortrait ? "bottom" : "right", shouldShow ? getResources().getDimensionPixelSize(R.dimen.titles_size) : 0), PropertyValuesHolder.ofFloat("alpha", shouldShow ? 1 : 0) ); // At each step of the animation, we'll perform layout by calling setLayoutParams. final ViewGroup.LayoutParams lp = titlesView.getLayoutParams(); objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { public void onAnimationUpdate(ValueAnimator valueAnimator) { // *** WARNING ***: triggering layout at each animation frame highly impacts // performance so you should only do this for simple layouts. More complicated // layouts can be better served with individual animations on child views to // avoid the performance penalty of layout. if (isPortrait) { lp.height = (Integer) valueAnimator.getAnimatedValue(); } else { lp.width = (Integer) valueAnimator.getAnimatedValue(); } titlesView.setLayoutParams(lp); } }); if (shouldShow) { fm.beginTransaction().show(f).commit(); objectAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animator) { mCurrentTitlesAnimator = null; } }); } else { objectAnimator.addListener(new AnimatorListenerAdapter() { boolean canceled; @Override public void onAnimationCancel(Animator animation) { canceled = true; super.onAnimationCancel(animation); } @Override public void onAnimationEnd(Animator animator) { if (canceled) return; mCurrentTitlesAnimator = null; fm.beginTransaction().hide(f).commit(); } }); } // Start the animation. objectAnimator.start(); mCurrentTitlesAnimator = objectAnimator; invalidateOptionsMenu(); // Manually trigger onNewIntent to check for ACTION_DIALOG. onNewIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { if (ACTION_DIALOG.equals(intent.getAction())) { showDialog(intent.getStringExtra(Intent.EXTRA_TEXT)); } } void showDialog(String text) { // 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(); DialogFragment newFragment = MyDialogFragment.newInstance(text); // Show the dialog. newFragment.show(ft, "dialog"); } void showNotification(boolean custom) { final Resources res = getResources(); final NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_stat_notify_example) .setAutoCancel(true) .setTicker(getString(R.string.notification_text)) .setContentIntent(getDialogPendingIntent("Tapped the notification entry.")); if (custom) { // Sets a custom content view for the notification, including an image button. RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification); layout.setTextViewText(R.id.notification_title, getString(R.string.app_name)); layout.setOnClickPendingIntent(R.id.notification_button, getDialogPendingIntent("Tapped the 'dialog' button in the notification.")); builder.setContent(layout); // Notifications in Android 3.0 now have a standard mechanism for displaying large // bitmaps such as contact avatars. Here, we load an example image and resize it to the // appropriate size for large bitmaps in notifications. Bitmap largeIconTemp = BitmapFactory.decodeResource(res, R.drawable.notification_default_largeicon); Bitmap largeIcon = Bitmap.createScaledBitmap( largeIconTemp, res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false); largeIconTemp.recycle(); builder.setLargeIcon(largeIcon); } else { builder .setNumber(7) // An example number. .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notification_text)); } notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification()); } PendingIntent getDialogPendingIntent(String dialogText) { return PendingIntent.getActivity( this, dialogText.hashCode(), // Otherwise previous PendingIntents with the same // requestCode may be overwritten. new Intent(ACTION_DIALOG) .putExtra(Intent.EXTRA_TEXT, dialogText) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.getItem(1).setTitle(mToggleLabels[mLabelIndex]); return true; } @Override public void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); ActionBar bar = getActionBar(); int category = bar.getSelectedTab().getPosition(); outState.putInt("category", category); outState.putInt("theme", mThemeId); } public static class MyDialogFragment extends DialogFragment { public static MyDialogFragment newInstance(String title) { MyDialogFragment frag = new MyDialogFragment(); Bundle args = new Bundle(); args.putString("text", title); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { String text = getArguments().getString("text"); return new AlertDialog.Builder(getActivity()) .setTitle("A Dialog of Awesome") .setMessage(text) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } } ) .create(); } } } //src\com\example\android\hcgallery\TitlesFragment.java /* * Copyright (C) 2011 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. */ package com.example.android.hcgallery; import android.app.Fragment; import android.app.FragmentManager; import android.app.ListFragment; import android.content.ClipData; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.text.TextPaint; import android.util.TypedValue; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemLongClickListener; public class TitlesFragment extends ListFragment { private int mCategory = 0; private int mCurPosition = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //Current position should survive screen rotations. if (savedInstanceState != null) { mCategory = savedInstanceState.getInt("category"); mCurPosition = savedInstanceState.getInt("listPosition"); } populateTitles(mCategory); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lv.setCacheColorHint(Color.TRANSPARENT); lv.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) { final String title = (String) ((TextView) v).getText(); // Set up clip data with the category||entry_id format. final String textData = String.format("%d||%d", mCategory, pos); ClipData data = ClipData.newPlainText(title, textData); v.startDrag(data, new MyDragShadowBuilder(v), null, 0); return true; } }); selectPosition(mCurPosition); } private class MyDragShadowBuilder extends View.DragShadowBuilder { private Drawable mShadow; public MyDragShadowBuilder(View v) { super(v); final TypedArray a = v.getContext().obtainStyledAttributes(R.styleable.AppTheme); mShadow = a.getDrawable(R.styleable.AppTheme_listDragShadowBackground); mShadow.setCallback(v); mShadow.setBounds(0, 0, v.getWidth(), v.getHeight()); a.recycle(); } @Override public void onDrawShadow(Canvas canvas) { super.onDrawShadow(canvas); mShadow.draw(canvas); getView().draw(canvas); } } public void populateTitles(int category) { DirectoryCategory cat = Directory.getCategory(category); String[] items = new String[cat.getEntryCount()]; for (int i = 0; i < cat.getEntryCount(); i++) items[i] = cat.getEntry(i).getName(); setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.title_list_item, items)); mCategory = category; } @Override public void onListItemClick(ListView l, View v, int position, long id) { updateImage(position); } private void updateImage(int position) { ContentFragment frag = (ContentFragment) getFragmentManager() .findFragmentById(R.id.frag_content); frag.updateContentAndRecycleBitmap(mCategory, position); mCurPosition = position; } public void selectPosition(int position) { ListView lv = getListView(); lv.setItemChecked(position, true); updateImage(position); } @Override public void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("listPosition", mCurPosition); outState.putInt("category", mCategory); } } // //res\layout\action_bar_custom.xml <!-- Copyright (C) 2011 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:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="match_parent">Hello Action Bar</TextView> </LinearLayout> //res\layout\camera_sample.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.android.hcgallery.CameraFragment" android:id="@+id/camera_frag" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> //res\layout\content_welcome.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <view xmlns:android="http://schemas.android.com/apk/res/android" class="com.example.android.hcgallery.FitCenterFrameLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="24dp" android:clickable="true"> <ImageView android:id="@+id/image" android:background="@drawable/picture_frame" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:duplicateParentState="true"/> </view> //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/frags"> <fragment class="com.example.android.hcgallery.TitlesFragment" android:id="@+id/frag_title" android:visibility="gone" android:layout_marginTop="?android:attr/actionBarSize" android:layout_width="@dimen/titles_size" android:layout_height="match_parent" /> <fragment class="com.example.android.hcgallery.ContentFragment" android:id="@+id/frag_content" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> //res\layout\notification.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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:id="@+id/notificationbg" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <LinearLayout android:paddingLeft="16dip" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/notification_title" style="@android:style/TextAppearance.StatusBar.EventContent.Title" android:focusable="true" android:ellipsize="marquee" android:singleLine="true" android:layout_gravity="left" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/notification_subtitle" style="@android:style/TextAppearance.StatusBar.EventContent" android:layout_gravity="left" android:maxLines="2" android:scrollHorizontally="true" android:ellipsize="end" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/notification_text" /> </LinearLayout> <ImageButton android:id="@+id/notification_button" android:src="@drawable/btn_notification_ic_example" android:background="@null" android:layout_weight="0" android:layout_width="48dip" android:layout_height="match_parent" /> </LinearLayout> //res\layout\title_list_item.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:gravity="bottom" android:textAppearance="?android:attr/textAppearanceMedium" android:background="?android:attr/activatedBackgroundIndicator" > </TextView> // //res\layout-port\main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/frags"> <fragment class="com.example.android.hcgallery.TitlesFragment" android:id="@+id/frag_title" android:visibility="gone" android:layout_marginTop="?android:attr/actionBarSize" android:layout_width="match_parent" android:layout_height="@dimen/titles_size"/> <fragment class="com.example.android.hcgallery.ContentFragment" android:id="@+id/frag_content" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> // //res\menu\camera_menu.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/switch_cam" android:title="Switch Camera" /> </menu> //res\menu\main_menu.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/camera" android:title="Camera" android:icon="?attr/menuIconCamera" android:showAsAction="ifRoom" /> <item android:id="@+id/toggleTitles" android:icon="?attr/menuIconToggle" android:title="Toggle Titles" android:showAsAction="ifRoom|withText" /> <!-- Example of items in the overflow menu --> <item android:id="@+id/toggleTheme" android:title="Day/Night" android:showAsAction="never" /> <item android:id="@+id/showDialog" android:title="Show a dialog" android:showAsAction="never" /> <item android:id="@+id/showStandardNotification" android:title="Show a basic notification" android:showAsAction="never" /> <item android:id="@+id/showCustomNotification" android:title="Show a custom notification" android:showAsAction="never" /> </menu> //res\menu\photo_context_menu.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/share" android:title="Share" android:icon="?attr/menuIconShare" android:showAsAction="always|withText" /> </menu> // //res\values\attrs.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <resources> <declare-styleable name="AppTheme"> <attr name="listDragShadowBackground" format="reference" /> <attr name="menuIconCamera" format="reference" /> <attr name="menuIconToggle" format="reference" /> <attr name="menuIconShare" format="reference" /> </declare-styleable> </resources> //res\values\colors.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <resources> <color name="actionbar_background_light">#ccffffff</color> <color name="actionbar_background_dark">#cc000000</color> <color name="drag_active_color">#80cccccc</color> </resources> //res\values\dimens.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <resources> <dimen name="titles_size">300dp</dimen> </resources> //res\values\strings.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. --> <resources> <string name="app_name">Honeycomb Gallery</string> <string name="camera_sample">Camera Example</string> <string name="clip_label">Clip Label</string> <string name="app_widget_name">Honeycomb Example Widget</string> <string name="widget_empty_view_text">Touch to show data</string> <string name="notification_text">Example notification text</string> <string name="photo_selection_cab_title">Photo selection</string> </resources> //res\values\styles.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <resources> <style name="ActionBar" parent="@android:style/Widget.Holo.ActionBar" /> <style name="ActionBar.Light" parent="@style/ActionBar"> <item name="android:background">@color/actionbar_background_light</item> </style> <style name="ActionBar.Dark" parent="@style/ActionBar"> <item name="android:background">@color/actionbar_background_dark</item> </style> <style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light"> <item name="android:actionBarStyle">@style/ActionBar.Light</item> <item name="android:windowActionBarOverlay">true</item> <item name="listDragShadowBackground">@android:color/background_light</item> <item name="menuIconCamera">@drawable/ic_menu_camera_holo_light</item> <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_light</item> <item name="menuIconShare">@drawable/ic_menu_share_holo_light</item> </style> <style name="AppTheme.Dark" parent="@android:style/Theme.Holo"> <item name="android:actionBarStyle">@style/ActionBar.Dark</item> <item name="android:windowActionBarOverlay">true</item> <item name="listDragShadowBackground">@android:color/background_dark</item> <item name="menuIconCamera">@drawable/ic_menu_camera_holo_dark</item> <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_dark</item> <item name="menuIconShare">@drawable/ic_menu_share_holo_dark</item> </style> </resources> // //res\values-port\dimens.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <resources> <dimen name="titles_size">200dp</dimen> </resources>
package app.test; import android.app.Activity; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.TextView; public class Test extends Activity { public final static int DISPLAYWIDTH = 200; public final static int DISPLAYHEIGHT = 200; TextView titleTextView; ImageButton imageButton; Cursor cursor; Bitmap bmp; String imageFilePath; int fileColumn; int titleColumn; int displayColumn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); titleTextView = (TextView) this.findViewById(R.id.TitleTextView); imageButton = (ImageButton) this.findViewById(R.id.ImageButton); String[] columns = { Media.DATA, Media._ID, Media.TITLE, Media.DISPLAY_NAME }; cursor = managedQuery(Media.EXTERNAL_CONTENT_URI, columns, null, null, null); fileColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); titleColumn = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.TITLE); displayColumn = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME); if (cursor.moveToFirst()) { titleTextView.setText(cursor.getString(displayColumn)); imageFilePath = cursor.getString(fileColumn); bmp = getBitmap(imageFilePath); imageButton.setImageBitmap(bmp); } imageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (cursor.moveToNext()) { titleTextView.setText(cursor.getString(displayColumn)); imageFilePath = cursor.getString(fileColumn); bmp = getBitmap(imageFilePath); imageButton.setImageBitmap(bmp); } } }); } private Bitmap getBitmap(String imageFilePath) { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions); bmpFactoryOptions.inSampleSize = 2; bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions); return bmp; } } //layout/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" > <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ImageButton"></ImageButton> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/TitleTextView" android:text="Image Title"/> </LinearLayout>
7-RadioGroup
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //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" android:stretchColumns="1" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" /> </TableRow> <TableRow> <TextView android:text="Type:" /> <RadioGroup android:id="@+id/types"> <RadioButton android:id="@+id/take_out" android:text="Take-Out" /> <RadioButton android:id="@+id/sit_down" android:text="Sit-Down" /> <RadioButton android:id="@+id/delivery" android:text="Delivery" /> </RadioGroup> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.RadioGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.LinearLayout; public class RadioGroup1 extends Activity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener { private TextView mChoice; private RadioGroup mRadioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.radio_group_1); mRadioGroup = (RadioGroup) findViewById(R.id.menu); // test adding a radio button programmatically RadioButton newRadioButton = new RadioButton(this); newRadioButton.setText(R.string.radio_group_snack); newRadioButton.setId(R.id.snack); LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); mRadioGroup.addView(newRadioButton, 0, layoutParams); // test listening to checked change events String selection = getString(R.string.radio_group_selection); mRadioGroup.setOnCheckedChangeListener(this); mChoice = (TextView) findViewById(R.id.choice); mChoice.setText(selection + mRadioGroup.getCheckedRadioButtonId()); } public void onCheckedChanged(RadioGroup group, int checkedId) { String selection = getString(R.string.radio_group_selection); String none = getString(R.string.radio_group_none); mChoice.setText(selection + (checkedId == View.NO_ID ? none : checkedId)); } public void onClick(View v) { mRadioGroup.clearCheck(); } } //layout/radio_group_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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="match_parent" android:orientation="vertical"> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:checkedButton="@+id/lunch" android:id="@+id/menu"> <RadioButton android:text="@string/radio_group_1_breakfast" android:id="@+id/breakfast" /> <RadioButton android:text="@string/radio_group_1_lunch" android:id="@id/lunch" /> <RadioButton android:text="@string/radio_group_1_dinner" android:id="@+id/dinner" /> <RadioButton android:text="@string/radio_group_1_all" android:id="@+id/all" /> <TextView android:text="@string/radio_group_1_selection" android:id="@+id/choice" /> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_group_1_clear" android:id="@+id/clear" /> </LinearLayout>
import java.io.BufferedInputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; class WidgetUtil { public static RadioGroup createRadioGroup(Context context){ return new RadioGroup(context); } public static RadioButton createRadioButton(Context context,String label,int id){ RadioButton bt= new RadioButton(context); bt.setId(id); bt.setText(label); return bt; } }
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.RadioGroup; import android.widget.Button; import android.widget.RadioButton; import android.widget.LinearLayout; public class RadioGroup1 extends Activity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener { private TextView mChoice; private RadioGroup mRadioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.radio_group_1); mRadioGroup = (RadioGroup) findViewById(R.id.menu); // test adding a radio button programmatically RadioButton newRadioButton = new RadioButton(this); newRadioButton.setText(R.string.radio_group_snack); newRadioButton.setId(R.id.snack); LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); mRadioGroup.addView(newRadioButton, 0, layoutParams); // test listening to checked change events String selection = getString(R.string.radio_group_selection); mRadioGroup.setOnCheckedChangeListener(this); mChoice = (TextView) findViewById(R.id.choice); mChoice.setText(selection + mRadioGroup.getCheckedRadioButtonId()); // test clearing the selection Button clearButton = (Button) findViewById(R.id.clear); clearButton.setOnClickListener(this); } public void onCheckedChanged(RadioGroup group, int checkedId) { String selection = getString(R.string.radio_group_selection); String none = getString(R.string.radio_group_none); mChoice.setText(selection + (checkedId == View.NO_ID ? none : checkedId)); } public void onClick(View v) { mRadioGroup.clearCheck(); } } //layout/radio_group_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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="match_parent" android:orientation="vertical"> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:checkedButton="@+id/lunch" android:id="@+id/menu"> <RadioButton android:text="@string/radio_group_1_breakfast" android:id="@+id/breakfast" /> <RadioButton android:text="@string/radio_group_1_lunch" android:id="@id/lunch" /> <RadioButton android:text="@string/radio_group_1_dinner" android:id="@+id/dinner" /> <RadioButton android:text="@string/radio_group_1_all" android:id="@+id/all" /> <TextView android:text="@string/radio_group_1_selection" android:id="@+id/choice" /> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/radio_group_1_clear" android:id="@+id/clear" /> </LinearLayout>
RadioGroup selection Changed Listener
package app.test; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.RadioGroup; public class Test extends Activity { protected static final String TAG = "RadioGroupActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); RadioGroup radGrp = (RadioGroup) findViewById(R.id.radGrp); int checkedRadioButtonID = radGrp.getCheckedRadioButtonId(); radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup arg0, int id) { switch (id) { case -1: Log.v(TAG, "Choices cleared!"); break; case R.id.chRBtn: Log.v(TAG, "Chose Chicken"); break; case R.id.fishRBtn: Log.v(TAG, "Chose Fish"); break; case R.id.stkRBtn: Log.v(TAG, "Chose Steak"); break; default: Log.v(TAG, "Huh?"); 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"> <RadioButton android:id="@+id/anotherRadBtn" android:text="Outside" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioGroup android:id="@+id/radGrp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <RadioButton android:id="@+id/chRBtn" android:text="Chicken" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/fishRBtn" android:text="Fish" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <RadioButton android:id="@+id/stkRBtn" android:text="Steak" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:text="My Favorite" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RadioGroup> </LinearLayout>
package app.test; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioGroup; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final RadioGroup radiogroup = (RadioGroup) findViewById(R.id.testRadioGroup); final Button changeButton = (Button) findViewById(R.id.enableButton); changeButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption(radiogroup); } }); final Button changeButton2 = (Button) findViewById(R.id.backgroundColorButton); changeButton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption2(radiogroup); } }); } public void changeOption(RadioGroup radiogroup) { if (radiogroup.isEnabled()) { radiogroup.setEnabled(false); } else { radiogroup.setEnabled(true); } } public void changeOption2(RadioGroup radiogroup) { radiogroup.setBackgroundColor(Color.RED); } } //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" > <RadioGroup android:id="@+id/testRadioGroup" android:layout_width="fill_parent" android:layout_height="wrap_content" > <RadioButton android:text="Radio 1" android:id="@+id/radio1" /> <RadioButton android:text="Radio 2" android:id="@+id/radio2" /> </RadioGroup> <Button android:id="@+id/enableButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Set isEnabled"/> <Button android:id="@+id/backgroundColorButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Background Color"/> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.widget.LinearLayout; import android.widget.RadioGroup; public class Test extends Activity implements RadioGroup.OnCheckedChangeListener { RadioGroup orientation; RadioGroup gravity; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); orientation = (RadioGroup) findViewById(R.id.orientation); orientation.setOnCheckedChangeListener(this); gravity = (RadioGroup) findViewById(R.id.gravity); gravity.setOnCheckedChangeListener(this); } public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.horizontal: orientation.setOrientation(LinearLayout.HORIZONTAL); break; case R.id.vertical: orientation.setOrientation(LinearLayout.VERTICAL); break; case R.id.left: gravity.setGravity(Gravity.LEFT); break; case R.id.center: gravity.setGravity(Gravity.CENTER_HORIZONTAL); break; case R.id.right: gravity.setGravity(Gravity.RIGHT); 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" > <RadioGroup android:id="@+id/orientation" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5px"> <RadioButton android:id="@+id/horizontal" android:text="horizontal" /> <RadioButton android:id="@+id/vertical" android:text="vertical" /> </RadioGroup> <RadioGroup android:id="@+id/gravity" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5px"> <RadioButton android:id="@+id/left" android:text="left" /> <RadioButton android:id="@+id/center" android:text="center" /> <RadioButton android:id="@+id/right" android:text="right" /> </RadioGroup> </LinearLayout>
8-LinearLayout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:id="@+id/url_field" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:lines="1" /> <Button android:id="@+id/go_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/go_button" /> </LinearLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; /** * Baseline alignment includes a {@link android.widget.LinearLayout} * within another {@link android.widget.LinearLayout}. */ public class BaselineNested3 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="3dip" android:layout_gravity="center_vertical" android:text="baseline_nested_1_label" /> <!-- We want the middle textview of this vertical linear layout to be baseline aligned with the others.--> <LinearLayout android:orientation="vertical" android:baselineAlignedChildIndex="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/arrow_up_float"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dip" android:text="baseline_nested_1_label" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/arrow_down_float"/> </LinearLayout> <!-- We'll point to the linear layout to baseline align by, which in turn will point to a text view inside of it --> <LinearLayout android:orientation="vertical" android:baselineAlignedChildIndex="1" android:layout_width="wrap_content" android:layout_gravity="center_vertical" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/arrow_up_float"/> <LinearLayout android:orientation="vertical" android:baselineAlignedChildIndex="2" android:layout_width="wrap_content" android:layout_gravity="center_vertical" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/arrow_up_float"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/arrow_up_float"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dip" android:text="baseline_nested_1_label"/> </LinearLayout> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:layout_gravity="center_vertical" android:text="baseline_nested_1_label" /> </LinearLayout>
package com.commonsware.android.eu4you; import android.app.ListActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class EU4You extends ListActivity { static private ArrayList<Country> EU=new ArrayList<Country>(); private WebView browser=null; static { EU.add(new Country(R.string.austria, R.drawable.austria, R.string.austria_url)); EU.add(new Country(R.string.belgium, R.drawable.belgium, R.string.belgium_url)); EU.add(new Country(R.string.bulgaria, R.drawable.bulgaria, R.string.bulgaria_url)); EU.add(new Country(R.string.cyprus, R.drawable.cyprus, R.string.cyprus_url)); EU.add(new Country(R.string.czech_republic, R.drawable.czech_republic, R.string.czech_republic_url)); EU.add(new Country(R.string.denmark, R.drawable.denmark, R.string.denmark_url)); EU.add(new Country(R.string.estonia, R.drawable.estonia, R.string.estonia_url)); EU.add(new Country(R.string.finland, R.drawable.finland, R.string.finland_url)); EU.add(new Country(R.string.france, R.drawable.france, R.string.france_url)); EU.add(new Country(R.string.germany, R.drawable.germany, R.string.germany_url)); EU.add(new Country(R.string.greece, R.drawable.greece, R.string.greece_url)); EU.add(new Country(R.string.hungary, R.drawable.hungary, R.string.hungary_url)); EU.add(new Country(R.string.ireland, R.drawable.ireland, R.string.ireland_url)); EU.add(new Country(R.string.italy, R.drawable.italy, R.string.italy_url)); EU.add(new Country(R.string.latvia, R.drawable.latvia, R.string.latvia_url)); EU.add(new Country(R.string.lithuania, R.drawable.lithuania, R.string.lithuania_url)); EU.add(new Country(R.string.luxembourg, R.drawable.luxembourg, R.string.luxembourg_url)); EU.add(new Country(R.string.malta, R.drawable.malta, R.string.malta_url)); EU.add(new Country(R.string.netherlands, R.drawable.netherlands, R.string.netherlands_url)); EU.add(new Country(R.string.poland, R.drawable.poland, R.string.poland_url)); EU.add(new Country(R.string.portugal, R.drawable.portugal, R.string.portugal_url)); EU.add(new Country(R.string.romania, R.drawable.romania, R.string.romania_url)); EU.add(new Country(R.string.slovakia, R.drawable.slovakia, R.string.slovakia_url)); EU.add(new Country(R.string.slovenia, R.drawable.slovenia, R.string.slovenia_url)); EU.add(new Country(R.string.spain, R.drawable.spain, R.string.spain_url)); EU.add(new Country(R.string.sweden, R.drawable.sweden, R.string.sweden_url)); EU.add(new Country(R.string.united_kingdom, R.drawable.united_kingdom, R.string.united_kingdom_url)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.browser); setListAdapter(new CountryAdapter()); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { String url=getString(EU.get(position).url); if (browser==null) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } else { browser.loadUrl(url); } } static class Country { int name; int flag; int url; Country(int name, int flag, int url) { this.name=name; this.flag=flag; this.url=url; } } class CountryAdapter extends ArrayAdapter<Country> { CountryAdapter() { super(EU4You.this, R.layout.row, R.id.name, EU); } @Override public View getView(int position, View convertView, ViewGroup parent) { CountryWrapper wrapper=null; if (convertView==null) { convertView=getLayoutInflater().inflate(R.layout.row, null); wrapper=new CountryWrapper(convertView); convertView.setTag(wrapper); } else { wrapper=(CountryWrapper)convertView.getTag(); } wrapper.populateFrom(getItem(position)); return(convertView); } } class CountryWrapper { private TextView name=null; private ImageView flag=null; private View row=null; CountryWrapper(View row) { this.row=row; } TextView getName() { if (name==null) { name=(TextView)row.findViewById(R.id.name); } return(name); } ImageView getFlag() { if (flag==null) { flag=(ImageView)row.findViewById(R.id.flag); } return(flag); } void populateFrom(Country nation) { getName().setText(nation.name); getFlag().setImageResource(nation.flag); } } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> //res\layout\row.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:padding="2dip" android:minHeight="?android:attr/listPreferredItemHeight" > <ImageView android:id="@+id/flag" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|left" android:paddingRight="4px" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|right" android:textSize="5mm" /> </LinearLayout> //res\layout-large-land\main.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="fill_parent" > <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <WebView android:id="@+id/browser" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">EU4You</string> <string name="austria">Austria</string> <string name="belgium">Belgium</string> <string name="bulgaria">Bulgaria</string> <string name="cyprus">Cyprus</string> <string name="czech_republic">Czech Republic</string> <string name="denmark">Denmark</string> <string name="estonia">Estonia</string> <string name="finland">Finland</string> <string name="france">France</string> <string name="germany">Germany</string> <string name="greece">Greece</string> <string name="hungary">Hungary</string> <string name="ireland">Ireland</string> <string name="italy">Italy</string> <string name="latvia">Latvia</string> <string name="lithuania">Lithuania</string> <string name="luxembourg">Luxembourg</string> <string name="malta">Malta</string> <string name="netherlands">Netherlands</string> <string name="poland">Poland</string> <string name="portugal">Portugal</string> <string name="romania">Romania</string> <string name="slovakia">Slovakia</string> <string name="slovenia">Slovenia</string> <string name="spain">Spain</string> <string name="sweden">Sweden</string> <string name="united_kingdom">United Kingdom</string> <string name="austria_url">http://en.m.wikipedia.org/wiki/Austria</string> <string name="belgium_url">http://en.m.wikipedia.org/wiki/Belgium</string> <string name="bulgaria_url">http://en.m.wikipedia.org/wiki/Bulgaria</string> <string name="cyprus_url">http://en.m.wikipedia.org/wiki/Cyprus</string> <string name="czech_republic_url">http://en.m.wikipedia.org/wiki/Czech_republic</string> <string name="denmark_url">http://en.m.wikipedia.org/wiki/Denmark</string> <string name="estonia_url">http://en.m.wikipedia.org/wiki/Estonia</string> <string name="finland_url">http://en.m.wikipedia.org/wiki/Finland</string> <string name="france_url">http://en.m.wikipedia.org/wiki/France</string> <string name="germany_url">http://en.m.wikipedia.org/wiki/Germany</string> <string name="greece_url">http://en.m.wikipedia.org/wiki/Greece</string> <string name="hungary_url">http://en.m.wikipedia.org/wiki/Hungary</string> <string name="ireland_url">http://en.m.wikipedia.org/wiki/Ireland</string> <string name="italy_url">http://en.m.wikipedia.org/wiki/Italy</string> <string name="latvia_url">http://en.m.wikipedia.org/wiki/Latvia</string> <string name="lithuania_url">http://en.m.wikipedia.org/wiki/Lithuania</string> <string name="luxembourg_url">http://en.m.wikipedia.org/wiki/Luxembourg</string> <string name="malta_url">http://en.m.wikipedia.org/wiki/Malta</string> <string name="netherlands_url">http://en.m.wikipedia.org/wiki/Netherlands</string> <string name="poland_url">http://en.m.wikipedia.org/wiki/Poland</string> <string name="portugal_url">http://en.m.wikipedia.org/wiki/Portugal</string> <string name="romania_url">http://en.m.wikipedia.org/wiki/Romania</string> <string name="slovakia_url">http://en.m.wikipedia.org/wiki/Slovakia</string> <string name="slovenia_url">http://en.m.wikipedia.org/wiki/Slovenia</string> <string name="spain_url">http://en.m.wikipedia.org/wiki/Spain</string> <string name="sweden_url">http://en.m.wikipedia.org/wiki/Sweden</string> <string name="united_kingdom_url">http://en.m.wikipedia.org/wiki/United_kingdom</string> </resources> Auto Complete Demo /*** Copyright (c) 2008-2009 CommonsWare, LLC 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. */ package com.commonsware.android.auto; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; public class AutoCompleteDemo extends Activity implements TextWatcher { TextView selection; AutoCompleteTextView edit; String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); selection=(TextView)findViewById(R.id.selection); edit=(AutoCompleteTextView)findViewById(R.id.edit); edit.addTextChangedListener(this); edit.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items)); } public void onTextChanged(CharSequence s, int start, int before, int count) { selection.setText(edit.getText()); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // needed for interface, but not used } public void afterTextChanged(Editable s) { // needed for interface, but not used } } //res\layout\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:id="@+id/selection" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <AutoCompleteTextView android:id="@+id/edit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:completionThreshold="3"/> </LinearLayout>
package com.commonsware.android.eu4you; import android.app.ListActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class EU4You extends ListActivity { static private ArrayList<Country> EU=new ArrayList<Country>(); static { EU.add(new Country(R.string.austria, R.drawable.austria, R.string.austria_url)); EU.add(new Country(R.string.belgium, R.drawable.belgium, R.string.belgium_url)); EU.add(new Country(R.string.bulgaria, R.drawable.bulgaria, R.string.bulgaria_url)); EU.add(new Country(R.string.cyprus, R.drawable.cyprus, R.string.cyprus_url)); EU.add(new Country(R.string.czech_republic, R.drawable.czech_republic, R.string.czech_republic_url)); EU.add(new Country(R.string.denmark, R.drawable.denmark, R.string.denmark_url)); EU.add(new Country(R.string.estonia, R.drawable.estonia, R.string.estonia_url)); EU.add(new Country(R.string.finland, R.drawable.finland, R.string.finland_url)); EU.add(new Country(R.string.france, R.drawable.france, R.string.france_url)); EU.add(new Country(R.string.germany, R.drawable.germany, R.string.germany_url)); EU.add(new Country(R.string.greece, R.drawable.greece, R.string.greece_url)); EU.add(new Country(R.string.hungary, R.drawable.hungary, R.string.hungary_url)); EU.add(new Country(R.string.ireland, R.drawable.ireland, R.string.ireland_url)); EU.add(new Country(R.string.italy, R.drawable.italy, R.string.italy_url)); EU.add(new Country(R.string.latvia, R.drawable.latvia, R.string.latvia_url)); EU.add(new Country(R.string.lithuania, R.drawable.lithuania, R.string.lithuania_url)); EU.add(new Country(R.string.luxembourg, R.drawable.luxembourg, R.string.luxembourg_url)); EU.add(new Country(R.string.malta, R.drawable.malta, R.string.malta_url)); EU.add(new Country(R.string.netherlands, R.drawable.netherlands, R.string.netherlands_url)); EU.add(new Country(R.string.poland, R.drawable.poland, R.string.poland_url)); EU.add(new Country(R.string.portugal, R.drawable.portugal, R.string.portugal_url)); EU.add(new Country(R.string.romania, R.drawable.romania, R.string.romania_url)); EU.add(new Country(R.string.slovakia, R.drawable.slovakia, R.string.slovakia_url)); EU.add(new Country(R.string.slovenia, R.drawable.slovenia, R.string.slovenia_url)); EU.add(new Country(R.string.spain, R.drawable.spain, R.string.spain_url)); EU.add(new Country(R.string.sweden, R.drawable.sweden, R.string.sweden_url)); EU.add(new Country(R.string.united_kingdom, R.drawable.united_kingdom, R.string.united_kingdom_url)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(new CountryAdapter()); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(EU.get(position).url)))); } static class Country { int name; int flag; int url; Country(int name, int flag, int url) { this.name=name; this.flag=flag; this.url=url; } } class CountryAdapter extends ArrayAdapter<Country> { CountryAdapter() { super(EU4You.this, R.layout.row, R.id.name, EU); } @Override public View getView(int position, View convertView, ViewGroup parent) { CountryWrapper wrapper=null; if (convertView==null) { convertView=getLayoutInflater().inflate(R.layout.row, null); wrapper=new CountryWrapper(convertView); convertView.setTag(wrapper); } else { wrapper=(CountryWrapper)convertView.getTag(); } wrapper.populateFrom(getItem(position)); return(convertView); } } class CountryWrapper { private TextView name=null; private ImageView flag=null; private View row=null; CountryWrapper(View row) { this.row=row; } TextView getName() { if (name==null) { name=(TextView)row.findViewById(R.id.name); } return(name); } ImageView getFlag() { if (flag==null) { flag=(ImageView)row.findViewById(R.id.flag); } return(flag); } void populateFrom(Country nation) { getName().setText(nation.name); getFlag().setImageResource(nation.flag); } } } <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <?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:padding="2dip" android:minHeight="?android:attr/listPreferredItemHeight" > <ImageView android:id="@+id/flag" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|left" android:paddingRight="4px" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|right" android:textSize="5mm" /> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">EU4You</string> <string name="austria">Austria</string> <string name="belgium">Belgium</string> <string name="bulgaria">Bulgaria</string> <string name="cyprus">Cyprus</string> <string name="czech_republic">Czech Republic</string> <string name="denmark">Denmark</string> <string name="estonia">Estonia</string> <string name="finland">Finland</string> <string name="france">France</string> <string name="germany">Germany</string> <string name="greece">Greece</string> <string name="hungary">Hungary</string> <string name="ireland">Ireland</string> <string name="italy">Italy</string> <string name="latvia">Latvia</string> <string name="lithuania">Lithuania</string> <string name="luxembourg">Luxembourg</string> <string name="malta">Malta</string> <string name="netherlands">Netherlands</string> <string name="poland">Poland</string> <string name="portugal">Portugal</string> <string name="romania">Romania</string> <string name="slovakia">Slovakia</string> <string name="slovenia">Slovenia</string> <string name="spain">Spain</string> <string name="sweden">Sweden</string> <string name="united_kingdom">United Kingdom</string> <string name="austria_url">http://en.m.wikipedia.org/wiki/Austria</string> <string name="belgium_url">http://en.m.wikipedia.org/wiki/Belgium</string> <string name="bulgaria_url">http://en.m.wikipedia.org/wiki/Bulgaria</string> <string name="cyprus_url">http://en.m.wikipedia.org/wiki/Cyprus</string> <string name="czech_republic_url">http://en.m.wikipedia.org/wiki/Czech_republic</string> <string name="denmark_url">http://en.m.wikipedia.org/wiki/Denmark</string> <string name="estonia_url">http://en.m.wikipedia.org/wiki/Estonia</string> <string name="finland_url">http://en.m.wikipedia.org/wiki/Finland</string> <string name="france_url">http://en.m.wikipedia.org/wiki/France</string> <string name="germany_url">http://en.m.wikipedia.org/wiki/Germany</string> <string name="greece_url">http://en.m.wikipedia.org/wiki/Greece</string> <string name="hungary_url">http://en.m.wikipedia.org/wiki/Hungary</string> <string name="ireland_url">http://en.m.wikipedia.org/wiki/Ireland</string> <string name="italy_url">http://en.m.wikipedia.org/wiki/Italy</string> <string name="latvia_url">http://en.m.wikipedia.org/wiki/Latvia</string> <string name="lithuania_url">http://en.m.wikipedia.org/wiki/Lithuania</string> <string name="luxembourg_url">http://en.m.wikipedia.org/wiki/Luxembourg</string> <string name="malta_url">http://en.m.wikipedia.org/wiki/Malta</string> <string name="netherlands_url">http://en.m.wikipedia.org/wiki/Netherlands</string> <string name="poland_url">http://en.m.wikipedia.org/wiki/Poland</string> <string name="portugal_url">http://en.m.wikipedia.org/wiki/Portugal</string> <string name="romania_url">http://en.m.wikipedia.org/wiki/Romania</string> <string name="slovakia_url">http://en.m.wikipedia.org/wiki/Slovakia</string> <string name="slovenia_url">http://en.m.wikipedia.org/wiki/Slovenia</string> <string name="spain_url">http://en.m.wikipedia.org/wiki/Spain</string> <string name="sweden_url">http://en.m.wikipedia.org/wiki/Sweden</string> <string name="united_kingdom_url">http://en.m.wikipedia.org/wiki/United_kingdom</string> </resources>
package com.commonsware.android.eu4you; import android.app.ListActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class EU4You extends ListActivity { static private ArrayList<Country> EU=new ArrayList<Country>(); static { EU.add(new Country(R.string.austria, R.drawable.austria, R.string.austria_url)); EU.add(new Country(R.string.belgium, R.drawable.belgium, R.string.belgium_url)); EU.add(new Country(R.string.bulgaria, R.drawable.bulgaria, R.string.bulgaria_url)); EU.add(new Country(R.string.cyprus, R.drawable.cyprus, R.string.cyprus_url)); EU.add(new Country(R.string.czech_republic, R.drawable.czech_republic, R.string.czech_republic_url)); EU.add(new Country(R.string.denmark, R.drawable.denmark, R.string.denmark_url)); EU.add(new Country(R.string.estonia, R.drawable.estonia, R.string.estonia_url)); EU.add(new Country(R.string.finland, R.drawable.finland, R.string.finland_url)); EU.add(new Country(R.string.france, R.drawable.france, R.string.france_url)); EU.add(new Country(R.string.germany, R.drawable.germany, R.string.germany_url)); EU.add(new Country(R.string.greece, R.drawable.greece, R.string.greece_url)); EU.add(new Country(R.string.hungary, R.drawable.hungary, R.string.hungary_url)); EU.add(new Country(R.string.ireland, R.drawable.ireland, R.string.ireland_url)); EU.add(new Country(R.string.italy, R.drawable.italy, R.string.italy_url)); EU.add(new Country(R.string.latvia, R.drawable.latvia, R.string.latvia_url)); EU.add(new Country(R.string.lithuania, R.drawable.lithuania, R.string.lithuania_url)); EU.add(new Country(R.string.luxembourg, R.drawable.luxembourg, R.string.luxembourg_url)); EU.add(new Country(R.string.malta, R.drawable.malta, R.string.malta_url)); EU.add(new Country(R.string.netherlands, R.drawable.netherlands, R.string.netherlands_url)); EU.add(new Country(R.string.poland, R.drawable.poland, R.string.poland_url)); EU.add(new Country(R.string.portugal, R.drawable.portugal, R.string.portugal_url)); EU.add(new Country(R.string.romania, R.drawable.romania, R.string.romania_url)); EU.add(new Country(R.string.slovakia, R.drawable.slovakia, R.string.slovakia_url)); EU.add(new Country(R.string.slovenia, R.drawable.slovenia, R.string.slovenia_url)); EU.add(new Country(R.string.spain, R.drawable.spain, R.string.spain_url)); EU.add(new Country(R.string.sweden, R.drawable.sweden, R.string.sweden_url)); EU.add(new Country(R.string.united_kingdom, R.drawable.united_kingdom, R.string.united_kingdom_url)); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(new CountryAdapter()); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(EU.get(position).url)))); } static class Country { int name; int flag; int url; Country(int name, int flag, int url) { this.name=name; this.flag=flag; this.url=url; } } class CountryAdapter extends ArrayAdapter<Country> { CountryAdapter() { super(EU4You.this, R.layout.row, R.id.name, EU); } @Override public View getView(int position, View convertView, ViewGroup parent) { CountryWrapper wrapper=null; if (convertView==null) { convertView=getLayoutInflater().inflate(R.layout.row, null); wrapper=new CountryWrapper(convertView); convertView.setTag(wrapper); } else { wrapper=(CountryWrapper)convertView.getTag(); } wrapper.populateFrom(getItem(position)); return(convertView); } } class CountryWrapper { private TextView name=null; private ImageView flag=null; private View row=null; CountryWrapper(View row) { this.row=row; } TextView getName() { if (name==null) { name=(TextView)row.findViewById(R.id.name); } return(name); } ImageView getFlag() { if (flag==null) { flag=(ImageView)row.findViewById(R.id.flag); } return(flag); } void populateFrom(Country nation) { getName().setText(nation.name); getFlag().setImageResource(nation.flag); } } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" /> //res\layout\row.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:padding="2dip" android:minHeight="?android:attr/listPreferredItemHeight" > <ImageView android:id="@+id/flag" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|left" android:paddingRight="4px" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|right" android:textSize="20px" /> </LinearLayout> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">EU4You</string> <string name="austria">Austria</string> <string name="belgium">Belgium</string> <string name="bulgaria">Bulgaria</string> <string name="cyprus">Cyprus</string> <string name="czech_republic">Czech Republic</string> <string name="denmark">Denmark</string> <string name="estonia">Estonia</string> <string name="finland">Finland</string> <string name="france">France</string> <string name="germany">Germany</string> <string name="greece">Greece</string> <string name="hungary">Hungary</string> <string name="ireland">Ireland</string> <string name="italy">Italy</string> <string name="latvia">Latvia</string> <string name="lithuania">Lithuania</string> <string name="luxembourg">Luxembourg</string> <string name="malta">Malta</string> <string name="netherlands">Netherlands</string> <string name="poland">Poland</string> <string name="portugal">Portugal</string> <string name="romania">Romania</string> <string name="slovakia">Slovakia</string> <string name="slovenia">Slovenia</string> <string name="spain">Spain</string> <string name="sweden">Sweden</string> <string name="united_kingdom">United Kingdom</string> <string name="austria_url">http://en.m.wikipedia.org/wiki/Austria</string> <string name="belgium_url">http://en.m.wikipedia.org/wiki/Belgium</string> <string name="bulgaria_url">http://en.m.wikipedia.org/wiki/Bulgaria</string> <string name="cyprus_url">http://en.m.wikipedia.org/wiki/Cyprus</string> <string name="czech_republic_url">http://en.m.wikipedia.org/wiki/Czech_republic</string> <string name="denmark_url">http://en.m.wikipedia.org/wiki/Denmark</string> <string name="estonia_url">http://en.m.wikipedia.org/wiki/Estonia</string> <string name="finland_url">http://en.m.wikipedia.org/wiki/Finland</string> <string name="france_url">http://en.m.wikipedia.org/wiki/France</string> <string name="germany_url">http://en.m.wikipedia.org/wiki/Germany</string> <string name="greece_url">http://en.m.wikipedia.org/wiki/Greece</string> <string name="hungary_url">http://en.m.wikipedia.org/wiki/Hungary</string> <string name="ireland_url">http://en.m.wikipedia.org/wiki/Ireland</string> <string name="italy_url">http://en.m.wikipedia.org/wiki/Italy</string> <string name="latvia_url">http://en.m.wikipedia.org/wiki/Latvia</string> <string name="lithuania_url">http://en.m.wikipedia.org/wiki/Lithuania</string> <string name="luxembourg_url">http://en.m.wikipedia.org/wiki/Luxembourg</string> <string name="malta_url">http://en.m.wikipedia.org/wiki/Malta</string> <string name="netherlands_url">http://en.m.wikipedia.org/wiki/Netherlands</string> <string name="poland_url">http://en.m.wikipedia.org/wiki/Poland</string> <string name="portugal_url">http://en.m.wikipedia.org/wiki/Portugal</string> <string name="romania_url">http://en.m.wikipedia.org/wiki/Romania</string> <string name="slovakia_url">http://en.m.wikipedia.org/wiki/Slovakia</string> <string name="slovenia_url">http://en.m.wikipedia.org/wiki/Slovenia</string> <string name="spain_url">http://en.m.wikipedia.org/wiki/Spain</string> <string name="sweden_url">http://en.m.wikipedia.org/wiki/Sweden</string> <string name="united_kingdom_url">http://en.m.wikipedia.org/wiki/United_kingdom</string> </resources>
//package com.reverb; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Paint.Style; import android.util.AttributeSet; import android.widget.LinearLayout; public class TransparentPanel extends LinearLayout { //Fields private Paint innerPaint, borderPaint; public TransparentPanel(Context context) { super(context); init(); } public TransparentPanel(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { innerPaint = new Paint(); innerPaint.setARGB(120, 170, 170, 170); // gray innerPaint.setAntiAlias(true); borderPaint = new Paint(); borderPaint.setARGB(230, 240, 240, 240); borderPaint.setAntiAlias(true); borderPaint.setStyle(Style.STROKE); borderPaint.setStrokeWidth(2); } @Override protected void dispatchDraw(Canvas canvas) { RectF drawRect = new RectF(); drawRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(drawRect, 5, 5, innerPaint); canvas.drawRoundRect(drawRect, 5, 5, borderPaint); super.dispatchDraw(canvas); } }
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.example.android.apis.R; public class ScrollBar3 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scrollbar3); findViewById(R.id.view3).setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET); } } //layout/scrollbar3.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- Demonstrates scrolling with a ScrollView. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ScrollView android:layout_width="100dip" android:layout_height="120dip" android:background="#FF0000"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_2_text" /> </LinearLayout> </ScrollView> <ScrollView android:layout_width="100dip" android:layout_height="120dip" android:background="#00FF00" android:paddingRight="12dip"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_3_text" android:textColor="#000000" android:background="#60AA60" /> </ScrollView> <ScrollView android:id="@+id/view3" android:layout_width="100dip" android:layout_height="120dip" android:background="@android:drawable/edit_text"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#000000" android:text="scrollbar_3_text" /> </ScrollView> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ScrollView android:id="@+id/view4" android:layout_width="100dip" android:layout_height="120dip" android:scrollbarStyle="outsideOverlay" android:background="@android:drawable/edit_text"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#000000" android:text="scrollbar_3_text" /> </ScrollView> <ScrollView android:id="@+id/view5" android:layout_width="100dip" android:layout_height="120dip" android:scrollbarStyle="outsideInset" android:background="@android:drawable/edit_text"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#000000" android:text="scrollbar_3_text" /> </ScrollView> </LinearLayout> </LinearLayout>
package com.example.android.apis.view; // Need the following import to get access to the app resources, since this // class is in a sub-package. import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; /** * Demonstrates using the uniformSize attribute * */ public class LinearLayout6 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.linear_layout_6); } } //layout/linear_layout_6.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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 which uses a combination of wrap_content on itself and match_parent on its children to get every item to be the same width. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@drawable/blue" android:padding="20dip" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:background="@drawable/box" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="linear_layout_6_one"/> <TextView android:background="@drawable/box" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="linear_layout_6_two"/> <TextView android:background="@drawable/box" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="linear_layout_6_three"/> <TextView android:background="@drawable/box" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="linear_layout_6_four"/> </LinearLayout>
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import com.example.android.apis.R; public class ImageButton1 extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_button_1); } } //image_button_1.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"> <ImageButton android:layout_width="100dip" android:layout_height="50dip" android:src="@android:drawable/sym_action_call" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/sym_action_chat" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/sym_action_email" /> </LinearLayout>
LinearLayout for ListAdapter
package app.test; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class Test extends ListActivity { private String[] data = {}; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)); } protected void onListItemClick(ListView listView, View v, int position, long id) { super.onListItemClick(listView, v, position, id); setTitle(listView.getItemAtPosition(position).toString()); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ListView android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent"/> <TextView android:id="@id/android:empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Empty"/> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; public class Test extends Activity { TextView myTextView; private static boolean inflate = true; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if (inflate) inflateXMLLayout(); else constructLayout(); } private void inflateXMLLayout() { setContentView(R.layout.main); myTextView = (TextView) findViewById(R.id.myTextView); } private void constructLayout() { LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); LinearLayout.LayoutParams textViewLP = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); myTextView = new TextView(this); myTextView.setText("Hello World, HelloWorld"); ll.addView(myTextView, textViewLP); addContentView(ll, lp); } } //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:id="@+id/myTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, HelloWorld" /> </LinearLayout>
Using LinearLayout to layout two RadioGroups
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.widget.LinearLayout; import android.widget.RadioGroup; public class Test extends Activity implements RadioGroup.OnCheckedChangeListener { RadioGroup orientation; RadioGroup gravity; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); orientation = (RadioGroup) findViewById(R.id.orientation); orientation.setOnCheckedChangeListener(this); gravity = (RadioGroup) findViewById(R.id.gravity); gravity.setOnCheckedChangeListener(this); } public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.horizontal: orientation.setOrientation(LinearLayout.HORIZONTAL); break; case R.id.vertical: orientation.setOrientation(LinearLayout.VERTICAL); break; case R.id.left: gravity.setGravity(Gravity.LEFT); break; case R.id.center: gravity.setGravity(Gravity.CENTER_HORIZONTAL); break; case R.id.right: gravity.setGravity(Gravity.RIGHT); 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" > <RadioGroup android:id="@+id/orientation" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5px"> <RadioButton android:id="@+id/horizontal" android:text="horizontal" /> <RadioButton android:id="@+id/vertical" android:text="vertical" /> </RadioGroup> <RadioGroup android:id="@+id/gravity" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5px"> <RadioButton android:id="@+id/left" android:text="left" /> <RadioButton android:id="@+id/center" android:text="center" /> <RadioButton android:id="@+id/right" android:text="right" /> </RadioGroup> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } //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="Hello World, FirstApp" /> </LinearLayout>
9-ImageView
package app.Test; import android.app.Activity; import android.os.Bundle; public class appTest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <SlidingDrawer android:id="@+id/drawer" android:layout_width="320dip" android:layout_height="440dip" android:orientation="vertical" android:handle="@+id/handle" android:content="@+id/content"> <ImageView android:id="@+id/handle" android:layout_width="48dip" android:layout_height="48dip" android:src="@drawable/icon" /> <AnalogClock android:id="@+id/content" android:background="#D0A0A0" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </SlidingDrawer> </RelativeLayout>
package app.test; import java.io.FileNotFoundException; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Test extends Activity implements OnClickListener { ImageView chosenImageView; Button choosePicture; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); chosenImageView = (ImageView) this.findViewById(R.id.ChosenImageView); choosePicture = (Button) this.findViewById(R.id.ChoosePictureButton); choosePicture.setOnClickListener(this); } public void onClick(View v) { Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(choosePictureIntent, 0); } protected void onActivityResult(int requestCode, int resultCode,Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (resultCode == RESULT_OK) { Uri imageFileUri = intent.getData(); Display currentDisplay = getWindowManager().getDefaultDisplay(); int dw = currentDisplay.getWidth(); int dh = currentDisplay.getHeight() / 2 - 100; try { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions); bmpFactoryOptions.inSampleSize = 2; bmpFactoryOptions.inJustDecodeBounds = false; bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream( imageFileUri), null, bmpFactoryOptions); chosenImageView.setImageBitmap(bmp); } catch (FileNotFoundException e) { Log.v("ERROR", e.toString()); } } } } //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" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Choose Picture" android:id="@+id/ChoosePictureButton"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ChosenImageView"></ImageView> </LinearLayout>
//package edi.android.library; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.concurrent.ConcurrentHashMap; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Handler; import android.util.Log; import android.widget.ImageView; /** * This helper class download images from the Internet and binds those with the * provided ImageView. * * <p> * It requires the INTERNET permission, which should be added to your * application's manifest file. * </p> * * A local cache of downloaded images is maintained internally to improve * performance. */ class ImageDownloader { private static final String LOG_TAG = ImageDownloader.class.getSimpleName(); private BitmapDownloaderTask task; /** * Download the specified image from the Internet and binds it to the * provided ImageView. The binding is immediate if the image is found in the * cache and will be done asynchronously otherwise. A null bitmap will be * associated to the ImageView if an error occurs. * * @param url * The URL of the image to download. * @param imageView * The ImageView to bind the downloaded image to. */ public void download(String url, ImageView imageView) { resetPurgeTimer(); Bitmap bitmap = getBitmapFromCache(url); if (bitmap == null) { forceDownload(url, imageView); } else { cancelPotentialDownload(url, imageView); imageView.setImageBitmap(bitmap); } } /* * Same as download but the image is always downloaded and the cache is not * used. Kept private at the moment as its interest is not clear. private * void forceDownload(String url, ImageView view) { forceDownload(url, view, * null); } */ /** * Same as download but the image is always downloaded and the cache is not * used. Kept private at the moment as its interest is not clear. */ private void forceDownload(String url, ImageView imageView) { // State sanity: url is guaranteed to never be null in // DownloadedDrawable and cache keys. if (url == null) { imageView.setImageDrawable(null); return; } if (cancelPotentialDownload(url, imageView)) { task = new BitmapDownloaderTask(imageView); DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task); imageView.setImageDrawable(downloadedDrawable); task.execute(url); } } /** * Returns true if the current download has been canceled or if there was no * download in progress on this image view. Returns false if the download in * progress deals with the same url. The download is not stopped in that * case. */ private static boolean cancelPotentialDownload(String url, ImageView imageView) { BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); if (bitmapDownloaderTask != null) { String bitmapUrl = bitmapDownloaderTask.url; if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) { bitmapDownloaderTask.cancel(true); } else { // The same URL is already being downloaded. return false; } } return true; } /** * @param imageView * Any imageView * @return Retrieve the currently active download task (if any) associated * with this imageView. null if there is no such task. */ private static BitmapDownloaderTask getBitmapDownloaderTask( ImageView imageView) { if (imageView != null) { Drawable drawable = imageView.getDrawable(); if (drawable instanceof DownloadedDrawable) { DownloadedDrawable downloadedDrawable = (DownloadedDrawable) drawable; return downloadedDrawable.getBitmapDownloaderTask(); } } return null; } Bitmap downloadBitmap(String url) { final int IO_BUFFER_SIZE = 4 * 1024; // AndroidHttpClient is not allowed to be used from the main thread final HttpClient client = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } else Log.d("ImageDownloader", "Success " + statusCode + " while retrieving bitmap from " + url); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. return BitmapFactory.decodeStream(new FlushedInputStream( inputStream)); } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(LOG_TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e); } return null; } /* * An InputStream that skips the exact number of bytes provided, unless it * reaches EOF. */ static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(InputStream inputStream) { super(inputStream); } @Override public long skip(long n) throws IOException { long totalBytesSkipped = 0L; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { int b = read(); if (b < 0) { break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } } /** * The actual AsyncTask that will asynchronously download the image. */ class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> { private String url; private final WeakReference<ImageView> imageViewReference; public BitmapDownloaderTask(ImageView imageView) { imageViewReference = new WeakReference<ImageView>(imageView); } /** * Actual download method. */ @Override protected Bitmap doInBackground(String... params) { url = params[0]; return downloadBitmap(url); } /** * Once the image is downloaded, associates it to the imageView */ @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } addBitmapToCache(url, bitmap); if (imageViewReference != null) { ImageView imageView = imageViewReference.get(); BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); // Change bitmap only if this process is still associated with // it // Or if we don't use any bitmap to task association // (NO_DOWNLOADED_DRAWABLE mode) if (this == bitmapDownloaderTask) { imageView.setImageBitmap(bitmap); } } } } /** * A fake Drawable that will be attached to the imageView while the download * is in progress. * * <p> * Contains a reference to the actual download task, so that a download task * can be stopped if a new binding is required, and makes sure that only the * last started download process can bind its result, independently of the * download finish order. * </p> */ static class DownloadedDrawable extends ColorDrawable { private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference; public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) { super(Color.BLACK); bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>( bitmapDownloaderTask); } public BitmapDownloaderTask getBitmapDownloaderTask() { return bitmapDownloaderTaskReference.get(); } } /* * Cache-related fields and methods. * * We use a hard and a soft cache. A soft reference cache is too * aggressively cleared by the Garbage Collector. */ private static final int HARD_CACHE_CAPACITY = 20; private static final int DELAY_BEFORE_PURGE = 120 * 1000; // in milliseconds // Hard cache, with a fixed maximum capacity and a life duration private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>( HARD_CACHE_CAPACITY / 2, 0.75f, true) { @Override protected boolean removeEldestEntry( LinkedHashMap.Entry<String, Bitmap> eldest) { if (size() > HARD_CACHE_CAPACITY) { // Entries push-out of hard reference cache are transferred to // soft reference cache sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue())); return true; } else return false; } }; // Soft cache for bitmaps kicked out of hard cache private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>( HARD_CACHE_CAPACITY / 2); private final Handler purgeHandler = new Handler(); private final Runnable purger = new Runnable() { public void run() { clearCache(); } }; /** * Adds this bitmap to the cache. * * @param bitmap * The newly downloaded bitmap. */ private void addBitmapToCache(String url, Bitmap bitmap) { if (bitmap != null) { synchronized (sHardBitmapCache) { sHardBitmapCache.put(url, bitmap); } } } /** * @param url * The URL of the image that will be retrieved from the cache. * @return The cached bitmap or null if it was not found. */ private Bitmap getBitmapFromCache(String url) { // First try the hard reference cache synchronized (sHardBitmapCache) { final Bitmap bitmap = sHardBitmapCache.get(url); if (bitmap != null) { // Bitmap found in hard cache // Move element to first position, so that it is removed last sHardBitmapCache.remove(url); sHardBitmapCache.put(url, bitmap); return bitmap; } } // Then try the soft reference cache SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url); if (bitmapReference != null) { final Bitmap bitmap = bitmapReference.get(); if (bitmap != null) { // Bitmap found in soft cache return bitmap; } else { // Soft reference has been Garbage Collected sSoftBitmapCache.remove(url); } } return null; } /** * Clears the image cache used internally to improve performance. Note that * for memory efficiency reasons, the cache will automatically be cleared * after a certain inactivity delay. */ public void clearCache() { sHardBitmapCache.clear(); sSoftBitmapCache.clear(); } /** * Allow a new delay before the automatic cache clear is done. */ private void resetPurgeTimer() { purgeHandler.removeCallbacks(purger); purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE); } }
//package com.retain; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.Date; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; /** * @author Nazmul Idris * @version 1.0 * @since Jul 8, 2008, 2:35:39 PM */ class AppUtils { /** * 127.0.0.1 in the emulator points back to itself. Use this if you want to * access your host OS */ public static String EmulatorLocalhost = "10.0.2.2"; /** * create an image view, given a drawable. you can set the max size of this * imageview as well. * * @param iconWidth * -1 means dont set this * @param iconHeight * -1 means dont set this * @param imageRes * -1 means dont set this */ public static ImageView createImageView(Context activity, int iconWidth, int iconHeight, int imageRes) { ImageView icon = new ImageView(activity); icon.setAdjustViewBounds(true); icon.setScaleType(ImageView.ScaleType.FIT_CENTER); if (iconHeight != -1) icon.setMaxHeight(iconHeight); if (iconWidth != -1) icon.setMaxWidth(iconWidth); if (imageRes != -1) icon.setImageResource(imageRes); return icon; } }// end class AppUtils
//package com.akjava.lib.android.ui; import java.io.BufferedInputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; class WidgetUtil { public static ImageView createImageView(Context context, int resid) { ImageView view=new ImageView(context); view.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), resid)); return view; } }
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import com.example.android.apis.R; /** * Demonstrates setting size constraints on {@link android.widget.ImageView} * */ public class ImageView1 extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_view_1); } } //image_view_1.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. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- The following four examples use a large image --> <!-- 1. Non-scaled view, for reference --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_large_normal"/> <ImageView android:src="@drawable/sample_1" android:adjustViewBounds="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 2. Limit to at most 50x50 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_large_at_most"/> <ImageView android:src="@drawable/sample_1" android:adjustViewBounds="true" android:maxWidth="50dip" android:maxHeight="50dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 3. Limit to at most 70x70, with 10 pixels of padding all around --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_large_at_most_padded"/> <ImageView android:src="@drawable/sample_1" android:background="#66FFFFFF" android:adjustViewBounds="true" android:maxWidth="70dip" android:maxHeight="70dip" android:padding="10dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 4. Limit to exactly 70x70, with 10 pixels of padding all around --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_large_exactly_padded"/> <ImageView android:src="@drawable/sample_1" android:background="#66FFFFFF" android:scaleType="centerInside" android:padding="10dip" android:layout_width="70dip" android:layout_height="70dip" /> <!-- Repeating the previous four examples with small image --> <!-- 1. Non-scaled view, for reference --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_small_normal"/> <ImageView android:src="@drawable/stat_happy" android:background="#FFFFFFFF" android:adjustViewBounds="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 2. Limit to at most 50x50 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_small_at_most"/> <ImageView android:src="@drawable/stat_happy" android:background="#FFFFFFFF" android:adjustViewBounds="true" android:maxWidth="50dip" android:maxHeight="50dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 3. Limit to at most 70x70, with 10 pixels of padding all around --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_small_at_most_padded"/> <ImageView android:src="@drawable/stat_happy" android:background="#FFFFFFFF" android:adjustViewBounds="true" android:maxWidth="70dip" android:maxHeight="70dip" android:padding="10dip" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <!-- 4. Limit to exactly 70x70, with 10 pixels of padding all around --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10dip" android:text="image_view_small_exactly_padded"/> <ImageView android:src="@drawable/stat_happy" android:background="#FFFFFFFF" android:scaleType="centerInside" android:padding="10dip" android:layout_width="70dip" android:layout_height="70dip" /> </LinearLayout> </ScrollView>
package app.test; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class Test extends Activity implements OnTouchListener { ImageView imageView; Bitmap bitmap; Canvas canvas; Paint paint; float downx = 0,downy = 0,upx = 0,upy = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imageView = (ImageView) this.findViewById(R.id.ImageView); Display currentDisplay = getWindowManager().getDefaultDisplay(); float dw = currentDisplay.getWidth(); float dh = currentDisplay.getHeight(); bitmap = Bitmap.createBitmap((int) dw, (int) dh, Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); paint = new Paint(); paint.setColor(Color.GREEN); imageView.setImageBitmap(bitmap); imageView.setOnTouchListener(this); } public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: downx = event.getX(); downy = event.getY(); break; case MotionEvent.ACTION_MOVE: upx = event.getX(); upy = event.getY(); canvas.drawLine(downx, downy, upx, upy, paint); imageView.invalidate(); downx = upx; downy = upy; break; case MotionEvent.ACTION_UP: upx = event.getX(); upy = event.getY(); canvas.drawLine(downx, downy, upx, upy, paint); imageView.invalidate(); break; case MotionEvent.ACTION_CANCEL: break; default: break; } return true; } }
Set image Uri for ImageView
package app.test; import android.app.Activity; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView = (ImageView) findViewById(R.id.image3); imgView.setImageURI(Uri.parse("file://mnt/sdcard/d2.jpg")); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is at /res/layout/list.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <ImageView android:id="@+id/image2" android:layout_width="125dip" android:layout_height="25dip" android:src="#555555" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image3" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" android:scaleType="centerInside" android:maxWidth="35dip" android:maxHeight="50dip" /> </LinearLayout> </LinearLayout>
package app.test; import android.app.Activity; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView = (ImageView)findViewById(R.id.image3); imgView.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.icon) ); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is at /res/layout/list.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <ImageView android:id="@+id/image2" android:layout_width="125dip" android:layout_height="25dip" android:src="#555555" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image3" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" android:scaleType="centerInside" android:maxWidth="35dip" android:maxHeight="50dip" /> </LinearLayout> </LinearLayout>
Set Image resource for ImageView
package app.test; import android.app.Activity; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.widget.ImageView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView = (ImageView)findViewById(R.id.image3); imgView.setImageResource( R.drawable.icon ); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is at /res/layout/list.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> <ImageView android:id="@+id/image2" android:layout_width="125dip" android:layout_height="25dip" android:src="#555555" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="fill_parent"> <ImageView android:id="@+id/image3" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" android:scaleType="centerInside" android:maxWidth="35dip" android:maxHeight="50dip" /> </LinearLayout> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; public class Test extends Activity{ private ImageView one = null; private ImageView two = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); one = (ImageView)findViewById(R.id.oneImgView); two = (ImageView)findViewById(R.id.twoImgView); one.setOnClickListener(new OnClickListener(){ public void onClick(View view) { two.setVisibility(View.VISIBLE); view.setVisibility(View.GONE); }}); two.setOnClickListener(new OnClickListener(){ public void onClick(View view) { one.setVisibility(View.VISIBLE); view.setVisibility(View.GONE); }}); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/frmLayout" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/oneImgView" android:src="@drawable/icon" android:scaleType="fitCenter" android:layout_width="fill_parent" android:layout_height="fill_parent"/> <ImageView android:id="@+id/twoImgView" android:src="@drawable/icon" android:scaleType="fitCenter" android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="gone" /> </FrameLayout>
package com.eoemobile.book.ex_widgetdemo; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; public class Test extends Activity { CheckBox plain_cb; CheckBox serif_cb; CheckBox italic_cb; CheckBox bold_cb; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("ImageViewActivity"); setContentView(R.layout.main); } } //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="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Image Display" /> <ImageView android:id="@+id/imagebutton" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
package app.test; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher; public class Test extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory { CheckBox plain_cb; CheckBox serif_cb; CheckBox italic_cb; CheckBox bold_cb; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); setTitle("ImageShowActivity"); mSwitcher = (ImageSwitcher) findViewById(R.id.switcher); mSwitcher.setFactory(this); mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)); Gallery g = (Gallery) findViewById(R.id.gallery); g.setAdapter(new ImageAdapter(this)); g.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView parent, View v, int position, long id) { mSwitcher.setImageResource(mImageIds[position]); } public void onNothingSelected(AdapterView parent) { } public View makeView() { ImageView i = new ImageView(this); i.setBackgroundColor(0xFF000000); i.setScaleType(ImageView.ScaleType.FIT_CENTER); i.setLayoutParams(new ImageSwitcher.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return i; } private ImageSwitcher mSwitcher; public class ImageAdapter extends BaseAdapter { public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); i.setImageResource(mThumbIds[position]); i.setAdjustViewBounds(true); i.setLayoutParams(new Gallery.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); i.setBackgroundResource(R.drawable.icon); return i; } private Context mContext; } private Integer[] mThumbIds = { R.drawable.icon, R.drawable.icon, }; private Integer[] mImageIds = { R.drawable.icon, R.drawable.icon }; } //main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageSwitcher android:id="@+id/switcher" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" /> <Gallery android:id="@+id/gallery" android:background="#55000000" android:layout_width="fill_parent" android:layout_height="60dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center_vertical" android:spacing="16dp" /> </RelativeLayout>
package app.test; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class Test extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);; setContentView(R.layout.main); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout android:id="@+id/left" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/photo" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } //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" > <ImageView android:id="@+id/imageview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/icon" /> </LinearLayout>
package com.commonsware.android.fancylists.four; import android.app.Activity; import android.os.Bundle; import android.app.ListActivity; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class RecyclingDemo extends ListActivity { TextView selection; String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new IconicAdapter()); selection=(TextView)findViewById(R.id.selection); } public void onListItemClick(ListView parent, View v, int position, long id) { selection.setText(items[position]); } class IconicAdapter extends ArrayAdapter { IconicAdapter() { super(RecyclingDemo.this, R.layout.row, items); } public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; if (row==null) { LayoutInflater inflater=getLayoutInflater(); row=inflater.inflate(R.layout.row, parent, false); } TextView label=(TextView)row.findViewById(R.id.label); label.setText(items[position]); ImageView icon=(ImageView)row.findViewById(R.id.icon); if (items[position].length()>4) { icon.setImageResource(R.drawable.delete); } else { icon.setImageResource(R.drawable.ok); } return(row); } } } // //res\layout\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:id="@+id/selection" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:drawSelectorOnTop="false" /> </LinearLayout> //res\layout\row.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="horizontal" > <ImageView android:id="@+id/icon" android:layout_width="22px" android:paddingLeft="2px" android:paddingRight="2px" android:paddingTop="2px" android:layout_height="wrap_content" android:src="@drawable/ok" /> <TextView android:id="@+id/label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } <?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/icon" android:layout_width="fill_parent" android:layout_height="fill_parent" android:adjustViewBounds="true" android:src="@drawable/icon" />
package app.test; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import org.apache.http.util.ByteArrayBuffer; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.util.AttributeSet; import android.widget.ImageView; class WebImageView extends ImageView { private Drawable mPlaceholder, mImage; public WebImageView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); } public void setPlaceholderImage(Drawable drawable) { mPlaceholder = drawable; if (mImage == null) { setImageDrawable(mPlaceholder); } } public void setPlaceholderImage(int resid) { mPlaceholder = getResources().getDrawable(resid); if (mImage == null) { setImageDrawable(mPlaceholder); } } public void setImageUrl(String url) { DownloadTask task = new DownloadTask(); task.execute(url); } private class DownloadTask extends AsyncTask<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... params) { String url = params[0]; try { BufferedInputStream bis = new BufferedInputStream((new URL(url)).openConnection().getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } byte[] imageData = baf.toByteArray(); return BitmapFactory.decodeByteArray(imageData, 0,imageData.length); } catch (Exception exc) { return null; } } @Override protected void onPostExecute(Bitmap result) { mImage = new BitmapDrawable(result); if (mImage != null) { setImageDrawable(mImage); } } }; } public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebImageView imageView = (WebImageView) findViewById(R.id.webImage); imageView.setPlaceholderImage(R.drawable.icon); imageView.setImageUrl("http://yourdomain.com/a.gif"); } } //main.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="fill_parent" android:orientation="vertical"> <app.test.WebImageView android:id="@+id/webImage" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
10-ListView
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.ExpandableListView; import android.content.Context; import android.graphics.Typeface; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ExpandableListView list = new ExpandableListView(this); list.setGroupIndicator(null); list.setChildIndicator(null); String[] titles = {"A","B","C"}; String[] fruits = {"a1","a2"}; String[] veggies = {"b1","b2","b3"}; String[] meats = {"c1","c2"}; String[][] contents = {fruits,veggies,meats}; SimplerExpandableListAdapter adapter = new SimplerExpandableListAdapter(this, titles, contents); list.setAdapter(adapter); setContentView(list); } } class SimplerExpandableListAdapter extends BaseExpandableListAdapter { private Context mContext; private String[][] mContents; private String[] mTitles; public SimplerExpandableListAdapter(Context context, String[] titles, String[][] contents) { super(); if(titles.length != contents.length) { throw new IllegalArgumentException("Titles and Contents must be the same size."); } mContext = context; mContents = contents; mTitles = titles; } @Override public String getChild(int groupPosition, int childPosition) { return mContents[groupPosition][childPosition]; } @Override public long getChildId(int groupPosition, int childPosition) { return 0; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { TextView row = (TextView)convertView; if(row == null) { row = new TextView(mContext); } row.setText(mContents[groupPosition][childPosition]); return row; } @Override public int getChildrenCount(int groupPosition) { return mContents[groupPosition].length; } @Override public String[] getGroup(int groupPosition) { return mContents[groupPosition]; } @Override public int getGroupCount() { return mContents.length; } @Override public long getGroupId(int groupPosition) { return 0; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView row = (TextView)convertView; if(row == null) { row = new TextView(mContext); } row.setTypeface(Typeface.DEFAULT_BOLD); row.setText(mTitles[groupPosition]); return row; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
//package com.akjava.lib.android.ui; import java.io.BufferedInputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; class WidgetUtil { //For List Activity public static ListView createListActivityList(Context context){ return createList(context, android.R.id.list); } public static ListView createList(Context context,int id){ ListView list=new ListView(context); list.setId(id); return list; } }
On nothing selected event
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; public class Test extends Activity { ListView listView; private String[] data = { "1", "2", "3","4", "5", "6" }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listView = new ListView(this); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)); setContentView(listView); OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) { setTitle("t: "+parent.getItemAtPosition(position).toString()); } @Override public void onNothingSelected(AdapterView<?> arg0) { setTitle(""); } }; listView.setOnItemSelectedListener(itemSelectedListener); } }
package app.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class Test extends Activity { private List<Map<String, Object>> data; private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PrepareData(); listView = new ListView(this); SimpleAdapter adapter = new SimpleAdapter(this, data,android.R.layout.simple_list_item_1, new String[] { "AAA" }, new int[] { android.R.id.text1 }); listView.setAdapter(adapter); setContentView(listView); OnItemClickListener listener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setTitle(parent.getItemAtPosition(position).toString()); } }; listView.setOnItemClickListener(listener); } private void PrepareData() { data = new ArrayList<Map<String, Object>>(); Map<String, Object> item; item = new HashMap<String, Object>(); item.put("1", "A"); item.put("2", "B"); data.add(item); item = new HashMap<String, Object>(); item.put("3", "C"); item.put("4", "D"); data.add(item); item = new HashMap<String, Object>(); item.put("5", "E"); item.put("6", "F"); data.add(item); } }
package apt.tutorial; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class LunchList extends Activity { Restaurant r=new Restaurant(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button save=(Button)findViewById(R.id.save); save.setOnClickListener(onSave); } private View.OnClickListener onSave=new View.OnClickListener() { public void onClick(View v) { EditText name=(EditText)findViewById(R.id.name); EditText address=(EditText)findViewById(R.id.addr); r.setName(name.getText().toString()); r.setAddress(address.getText().toString()); } }; } package apt.tutorial; public class Restaurant { private String name=""; private String address=""; public String getName() { return(name); } public void setName(String name) { this.name=name; } public String getAddress() { return(address); } public void setAddress(String address) { this.address=address; } } //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" > <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name:" /> <EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address:" /> <EditText android:id="@+id/addr" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LunchList</string> </resources>
package app.test; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioGroup; public class Test extends Activity { List<Restaurant> model = new ArrayList<Restaurant>(); ArrayAdapter<Restaurant> adapter = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button save = (Button) findViewById(R.id.save); save.setOnClickListener(onSave); ListView list = (ListView) findViewById(R.id.restaurants); adapter = new ArrayAdapter<Restaurant>(this, android.R.layout.simple_list_item_1, model); list.setAdapter(adapter); } private View.OnClickListener onSave = new View.OnClickListener() { public void onClick(View v) { Restaurant r = new Restaurant(); EditText name = (EditText) findViewById(R.id.name); EditText address = (EditText) findViewById(R.id.addr); r.setName(name.getText().toString()); r.setAddress(address.getText().toString()); RadioGroup types = (RadioGroup) findViewById(R.id.types); switch (types.getCheckedRadioButtonId()) { case R.id.sit_down: r.setType("sit_down"); break; case R.id.take_out: r.setType("take_out"); break; case R.id.delivery: r.setType("delivery"); break; } adapter.add(r); } }; } class Restaurant { private String name = ""; private String address = ""; private String type = ""; public String getName() { return (name); } public void setName(String name) { this.name = name; } public String getAddress() { return (address); } public void setAddress(String address) { this.address = address; } public String getType() { return (type); } public void setType(String type) { this.type = type; } } //main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableLayout android:id="@+id/details" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:stretchColumns="1" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" /> </TableRow> <TableRow> <TextView android:text="Type:" /> <RadioGroup android:id="@+id/types"> <RadioButton android:id="@+id/take_out" android:text="Take-Out" /> <RadioButton android:id="@+id/sit_down" android:text="Sit-Down" /> <RadioButton android:id="@+id/delivery" android:text="Delivery" /> </RadioGroup> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout> <ListView android:id="@+id/restaurants" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_above="@id/details" /> </RelativeLayout>
//package com.omareitti; import java.util.List; import java.util.UUID; import android.app.Activity; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcelable; import android.telephony.TelephonyManager; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; public class Utils { public static void setListViewHeightBasedOnChildren(ListView listView) { ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); listView.requestLayout(); } }
//package com.FileBrowser; import java.io.File; import java.util.ArrayList; import java.util.Collections; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; interface OnFileSelectedListener { public void onSelected(String path, String fileName); } interface OnNotifyEventListener { public void onNotify(Object sender); } interface OnPathChangedListener { public void onChanged(String path); } public 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); } } }; }
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.ListActivity; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; /** * This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL, a.k.a. selection mode on ListView. */ public class List15 extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); lv.setMultiChoiceModeListener(new ModeCallback()); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, mStrings)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActionBar().setSubtitle("Long press to start selection"); } private class ModeCallback implements ListView.MultiChoiceModeListener { public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_select_menu, menu); mode.setTitle("Select Items"); setSubtitle(mode); return true; } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.share: Toast.makeText(List15.this, "Shared " + getListView().getCheckedItemCount() + " items", Toast.LENGTH_SHORT).show(); mode.finish(); break; default: Toast.makeText(List15.this, "Clicked " + item.getTitle(), Toast.LENGTH_SHORT).show(); break; } return true; } public void onDestroyActionMode(ActionMode mode) { } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { setSubtitle(mode); } private void setSubtitle(ActionMode mode) { final int checkedCount = getListView().getCheckedItemCount(); switch (checkedCount) { case 0: mode.setSubtitle(null); break; case 1: mode.setSubtitle("One item selected"); break; default: mode.setSubtitle("" + checkedCount + " items selected"); break; } } } private String[] mStrings = Cheeses.sCheeseStrings; } class Cheeses { public static final String[] sCheeseStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese", "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell", "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc", "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss", "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon", "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase", "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese", "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy", "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille", "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore", "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)", "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves", "Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur", "Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon", "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin", "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)", "Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine", "Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza", "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)", "Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie", "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou", "Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar", "Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno", "Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack", "Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper", "Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)", "Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese", "Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza", "Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley", "Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino", "Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina", "Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby", "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin", "Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester", "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich", "Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue", "Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle", "Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia", "Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis", "Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus", "Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison", "Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois", "Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse", "Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese", "Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise", "Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola", "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost", "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi", "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa", "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger", "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin", "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio", "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel", "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela", "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse", "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone", "Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark", "Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit", "Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia", "Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)", "Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna", "Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera", "Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou", "Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder", "Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort", "Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr", "Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin", "Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre", "Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss", "Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela", "Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda", "Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain", "Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese", "Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale", "Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie", "Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri", "Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar", "Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance", "Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes", "Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet", "Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe", "Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa", "Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois", "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue", "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington", "Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou", "Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue", "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano" }; } //menu/list_select_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/share" android:title="@string/share" android:icon="@android:drawable/ic_menu_share" android:showAsAction="always" /> </menu>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.ListActivity; import android.content.Context; import android.graphics.PixelFormat; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.LayoutInflater; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.widget.AbsListView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class List9 extends ListActivity implements ListView.OnScrollListener { private final class RemoveWindow implements Runnable { public void run() { removeWindow(); } } private RemoveWindow mRemoveWindow = new RemoveWindow(); Handler mHandler = new Handler(); private WindowManager mWindowManager; private TextView mDialogText; private boolean mShowing; private boolean mReady; private char mPrevLetter = Character.MIN_VALUE; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWindowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE); // Use an existing ListAdapter that will map an array // of strings to TextViews setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); getListView().setOnScrollListener(this); LayoutInflater inflate = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); mDialogText = (TextView) inflate.inflate(R.layout.list_position, null); mDialogText.setVisibility(View.INVISIBLE); mHandler.post(new Runnable() { public void run() { mReady = true; WindowManager.LayoutParams lp = new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); mWindowManager.addView(mDialogText, lp); }}); } @Override protected void onResume() { super.onResume(); mReady = true; } @Override protected void onPause() { super.onPause(); removeWindow(); mReady = false; } @Override protected void onDestroy() { super.onDestroy(); mWindowManager.removeView(mDialogText); mReady = false; } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mReady) { char firstLetter = mStrings[firstVisibleItem].charAt(0); if (!mShowing && firstLetter != mPrevLetter) { mShowing = true; mDialogText.setVisibility(View.VISIBLE); } mDialogText.setText(((Character)firstLetter).toString()); mHandler.removeCallbacks(mRemoveWindow); mHandler.postDelayed(mRemoveWindow, 3000); mPrevLetter = firstLetter; } } public void onScrollStateChanged(AbsListView view, int scrollState) { } private void removeWindow() { if (mShowing) { mShowing = false; mDialogText.setVisibility(View.INVISIBLE); } } private String[] mStrings = Cheeses.sCheeseStrings; } class Cheeses { public static final String[] sCheeseStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese", "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell", "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc", "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss", "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon", "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase", "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese", "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy", "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille", "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore", "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)", "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves", "Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur", "Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon", "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin", "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)", "Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine", "Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza", "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)", "Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie", "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou", "Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar", "Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno", "Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack", "Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper", "Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)", "Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese", "Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza", "Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley", "Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino", "Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina", "Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby", "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin", "Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester", "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich", "Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue", "Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle", "Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia", "Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis", "Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus", "Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison", "Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois", "Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse", "Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese", "Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise", "Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola", "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost", "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi", "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa", "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger", "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin", "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio", "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel", "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela", "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse", "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone", "Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark", "Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit", "Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia", "Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)", "Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna", "Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera", "Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou", "Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder", "Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort", "Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr", "Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin", "Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre", "Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss", "Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela", "Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda", "Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain", "Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese", "Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale", "Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie", "Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri", "Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar", "Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance", "Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes", "Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet", "Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe", "Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa", "Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois", "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue", "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington", "Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou", "Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue", "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano" }; } //list_position.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:textSize="50sp" android:textColor="#99FFFFFF" android:background="#BB000000" android:minWidth="70dip" android:maxWidth="70dip" android:padding="10dip" android:gravity="center" />
package app.test; import android.app.ListActivity; import android.content.ContentUris; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class Test extends ListActivity { private static final String TAG = "ListViewActivity4"; private static final Uri CONTACTS_URI = ContactsContract.Contacts.CONTENT_URI; private SimpleCursorAdapter adapter = null; private ListView lv = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = getListView(); String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME}; Cursor c = managedQuery(CONTACTS_URI, projection, null, null, ContactsContract.Contacts.DISPLAY_NAME); String[] cols = new String[]{ContactsContract.Contacts.DISPLAY_NAME}; int[] views = new int[] {android.R.id.text1}; adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, c, cols, views); this.setListAdapter(adapter); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } public void doClick(View view) { if(!adapter.hasStableIds()) { Log.v(TAG, "Data is not stable"); return; } long[] viewItems = lv.getCheckedItemIds(); for(int i=0; i<viewItems.length; i++) { Uri selectedPerson = ContentUris.withAppendedId( CONTACTS_URI, viewItems[i]); Log.v(TAG, selectedPerson.toString() + " is checked."); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is at /res/layout/list.xml --> <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="@android:id/list" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> <Button android:id="@+id/btn" android:onClick="doClick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Submit Selection" /> </LinearLayout>
package app.test; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts.People; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.AdapterView.OnItemClickListener; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); String dataPath = getIntent().getData().toString(); final Uri data = Uri.parse(dataPath + "people/"); final Cursor c = managedQuery(data, null, null, null, null); String[] from = new String[] {People.NAME}; int[] to = new int[] { R.id.itemTextView }; SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.listitemlayout, c, from, to); ListView lv = (ListView)findViewById(R.id.contactListView); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { c.moveToPosition(pos); int rowId = c.getInt(c.getColumnIndexOrThrow("_id")); Uri outURI = Uri.parse(data.toString() + rowId); Intent outData = new Intent(); outData.setData(outURI); setResult(Activity.RESULT_OK, outData); finish(); } }); } } //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:id="@+id/itemTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10px" android:textSize="16px" android:textColor="#FFF" /> </LinearLayout>
Provide xml layout for ListView Item
package app.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class Test extends Activity { private List<Map<String, Object>> data; private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PrepareData(); listView = new ListView(this); SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.main, new String[] { "A", "B" }, new int[] { R.id.mview1, R.id.mview2 }); listView.setAdapter(adapter); setContentView(listView); OnItemClickListener listener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setTitle(parent.getItemAtPosition(position).toString()); } }; listView.setOnItemClickListener(listener); } private void PrepareData() { data = new ArrayList<Map<String, Object>>(); Map<String, Object> item; item = new HashMap<String, Object>(); item.put("1", "A"); item.put("2", "B"); data.add(item); item = new HashMap<String, Object>(); item.put("3", "C"); item.put("4", "D"); data.add(item); item = new HashMap<String, Object>(); item.put("5", "E"); item.put("6", "F"); data.add(item); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/mview1" android:layout_width="100px" android:layout_height="wrap_content" /> <TextView android:id="@+id/mview2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package app.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class Test extends Activity { private List<Map<String, Object>> data; private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PrepareData(); listView = new ListView(this); SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] { "1","2" }, new int[] { android.R.id.text1 , android.R.id.text2}); listView.setAdapter(adapter); setContentView(listView); OnItemClickListener listener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setTitle(parent.getItemAtPosition(position).toString()); } }; listView.setOnItemClickListener(listener); } private void PrepareData() { data = new ArrayList<Map<String, Object>>(); Map<String, Object> item; item = new HashMap<String, Object>(); item.put("1", "A"); item.put("2", "B"); data.add(item); item = new HashMap<String, Object>(); item.put("3", "C"); item.put("4", "D"); data.add(item); item = new HashMap<String, Object>(); item.put("5", "E"); item.put("6", "F"); data.add(item); } }
Using SimpleAdapter to fill data to ListView
package app.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class Test extends Activity { private List<Map<String, Object>> data; private ListView listView = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PrepareData(); listView = new ListView(this); SimpleAdapter adapter = new SimpleAdapter(this, data,android.R.layout.simple_list_item_1, new String[] { "AAA" }, new int[] { android.R.id.text1 }); listView.setAdapter(adapter); setContentView(listView); OnItemClickListener listener = new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { setTitle(parent.getItemAtPosition(position).toString()); } }; listView.setOnItemClickListener(listener); } private void PrepareData() { data = new ArrayList<Map<String, Object>>(); Map<String, Object> item; item = new HashMap<String, Object>(); item.put("1", "A"); item.put("2", "B"); data.add(item); item = new HashMap<String, Object>(); item.put("3", "C"); item.put("4", "D"); data.add(item); item = new HashMap<String, Object>(); item.put("5", "E"); item.put("6", "F"); data.add(item); } }
package com.commonsware.android.fancylists.seven; import android.database.DataSetObserver; import android.widget.ListAdapter; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; public class AdapterWrapper implements ListAdapter { ListAdapter delegate=null; public AdapterWrapper(ListAdapter delegate) { this.delegate=delegate; } public int getCount() { return(delegate.getCount()); } public Object getItem(int position) { return(delegate.getItem(position)); } public long getItemId(int position) { return(delegate.getItemId(position)); } public View getView(int position, View convertView, ViewGroup parent) { return(delegate.getView(position, convertView, parent)); } public void registerDataSetObserver(DataSetObserver observer) { delegate.registerDataSetObserver(observer); } public boolean hasStableIds() { return(delegate.hasStableIds()); } public boolean isEmpty() { return(delegate.isEmpty()); } public int getViewTypeCount() { return(delegate.getViewTypeCount()); } public int getItemViewType(int position) { return(delegate.getItemViewType(position)); } public void unregisterDataSetObserver(DataSetObserver observer) { delegate.unregisterDataSetObserver(observer); } public boolean areAllItemsEnabled() { return(delegate.areAllItemsEnabled()); } public boolean isEnabled(int position) { return(delegate.isEnabled(position)); } } //src\com\commonsware\android\fancylists\seven\RateListView.java package com.commonsware.android.fancylists.seven; import android.content.Context; import android.util.AttributeSet; import android.widget.ListAdapter; import android.widget.ListView; public class RateListView extends ListView { public RateListView(Context context) { super(context); } public RateListView(Context context, AttributeSet attrs) { super(context, attrs); } public RateListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setAdapter(ListAdapter adapter) { super.setAdapter(new RateableWrapper(getContext(), adapter)); } } //src\com\commonsware\android\fancylists\seven\RateListViewDemo.java package com.commonsware.android.fancylists.seven; import android.app.Activity; import android.os.Bundle; import android.app.ListActivity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.RatingBar; import android.widget.CompoundButton; import android.widget.ListView; public class RateListViewDemo extends ListActivity { String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi", "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam", "vel", "erat", "placerat", "ante", "porttitor", "sodales", "pellentesque", "augue", "purus"}; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items)); } } //src\com\commonsware\android\fancylists\seven\RateableWrapper.java package com.commonsware.android.fancylists.seven; import android.content.Context; import android.database.DataSetObserver; import android.widget.ListAdapter; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.RatingBar; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; public class RateableWrapper extends AdapterWrapper { Context ctxt=null; float[] rates=null; public RateableWrapper(Context ctxt, ListAdapter delegate) { super(delegate); this.ctxt=ctxt; this.rates=new float[delegate.getCount()]; for (int i=0;i<delegate.getCount();i++) { this.rates[i]=2.0f; } } public View getView(int position, View convertView, ViewGroup parent) { ViewWrapper wrap=null; View row=convertView; if (convertView==null) { LinearLayout layout=new LinearLayout(ctxt); RatingBar rate=new RatingBar(ctxt); rate.setNumStars(3); rate.setStepSize(1.0f); View guts=delegate.getView(position, null, parent); layout.setOrientation(LinearLayout.HORIZONTAL); rate.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT)); guts.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); RatingBar.OnRatingBarChangeListener l= new RatingBar.OnRatingBarChangeListener() { public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromTouch) { rates[(Integer)ratingBar.getTag()]=rating; } }; rate.setOnRatingBarChangeListener(l); layout.addView(rate); layout.addView(guts); wrap=new ViewWrapper(layout); wrap.setGuts(guts); layout.setTag(wrap); rate.setTag(new Integer(position)); rate.setRating(rates[position]); row=layout; } else { wrap=(ViewWrapper)convertView.getTag(); wrap.setGuts(delegate.getView(position, wrap.getGuts(), parent)); wrap.getRatingBar().setTag(new Integer(position)); wrap.getRatingBar().setRating(rates[position]); } return(row); } } //src\com\commonsware\android\fancylists\seven\ViewWrapper.java package com.commonsware.android.fancylists.seven; import android.view.View; import android.view.ViewGroup; import android.widget.RatingBar; class ViewWrapper { ViewGroup base; View guts=null; RatingBar rate=null; ViewWrapper(ViewGroup base) { this.base=base; } RatingBar getRatingBar() { if (rate==null) { rate=(RatingBar)base.getChildAt(0); } return(rate); } void setRatingBar(RatingBar rate) { this.rate=rate; } View getGuts() { if (guts==null) { guts=base.getChildAt(1); } return(guts); } void setGuts(View guts) { this.guts=guts; } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <com.commonsware.android.fancylists.seven.RateListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:drawSelectorOnTop="false" />
11-View
//package org.openintents.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Shader; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * BrightnessSlider. * * @author Peli, based on API demo code. * */ public class ColorSlider extends View { /** Default widget width */ public int defaultWidth; /** Default widget height */ public int defaultHeight; private Paint mPaint; private int mColor1; private int mColor2; private OnColorChangedListener mListener; /** * Constructor. This version is only needed for instantiating the object * manually (not from a layout XML file). * * @param context */ public ColorSlider(Context context) { super(context); init(); } /** * Construct object, initializing with any attributes we understand from a * layout file. * * These attributes are defined in res/values/attrs.xml . * * @see android.view.View#View(android.content.Context, * android.util.AttributeSet, java.util.Map) */ public ColorSlider(Context context, AttributeSet attrs) { super(context, attrs); // TODO what happens with inflateParams init(); } /** * Initializes variables. */ void init() { mColor1 = 0xFFFFFFFF; mColor2 = 0xFF000000; mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStyle(Paint.Style.FILL); } @Override protected void onDraw(Canvas canvas) { Shader s = new LinearGradient(0, 0, 0, getHeight(), mColor1, mColor2, Shader.TileMode.CLAMP); mPaint.setShader(s); canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint); } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * Determines the width of this view * * @param measureSpec * A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Default width: result = defaultWidth; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by // measureSpec result = Math.min(result, specSize); } } return result; } /** * Determines the height of this view * * @param measureSpec * A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Default height result = defaultHeight; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by // measureSpec result = Math.min(result, specSize); } } return result; } public void setColors(int color1, int color2) { mColor1 = color1; mColor2 = color2; invalidate(); } public void setOnColorChangedListener( OnColorChangedListener colorListener) { mListener = colorListener; } private int ave(int s, int d, float p) { return s + java.lang.Math.round(p * (d - s)); } private int interpColor(int color1, int color2, float unit) { if (unit <= 0) { return color1; } if (unit >= 1) { return color2; } float p = unit; // now p is just the fractional part [0...1) and i is the index int c0 = color1; int c1 = color2; 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); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: float unit = (float) y / ((float) getHeight()); int newcolor = interpColor(mColor1, mColor2, unit); if (mListener != null) { mListener.onColorChanged(this, newcolor); } invalidate(); break; case MotionEvent.ACTION_UP: break; } return true; } } /** * Interface for notifications of position change of slider. * * @author Peli */ interface OnColorChangedListener { /** * This method is called when the user changed the color. * * This works in touch mode, by dragging the along the * color circle with the finger. */ void onColorChanged(View view, int newColor); /** * This method is called when the user clicks the center button. * * @param colorcircle * @param newColor */ void onColorPicked(View view, int newColor); }
//package org.anddev.andengine.util; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; class ViewUtils { public static View inflate(final Context pContext, final int pLayoutID){ return LayoutInflater.from(pContext).inflate(pLayoutID, null); } public static View inflate(final Context pContext, final int pLayoutID, final ViewGroup pViewGroup){ return LayoutInflater.from(pContext).inflate(pLayoutID, pViewGroup, true); } }
import java.util.logging.Logger; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; class GraphView extends Visualizer { private static final String TAG = "GraphView"; private Bitmap mBitmap; private Canvas mCanvas = new Canvas(); private float mSpeed = 1f; private float mLastX; private float[] mLastValue = new float[10]; // 10 should be more than enough private int[] mColor = new int[4]; public GraphView(Context context) { super(context); init(); } public GraphView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { mColor[0] = Color.argb(255, 100, 255, 100); // g mColor[1] = Color.argb(255, 255, 255, 100); // y mColor[2] = Color.argb(255, 255, 100, 100); // r mColor[3] = Color.argb(255, 100, 255, 255); // c mPaint.setFlags(Paint.ANTI_ALIAS_FLAG); } public void setData(float value) { addDataPoint(value, mColor[0], mLastValue[0], 0); invalidate(); } public void setData(float[] values) { final int length = values.length; try { for (int i = 0; i < length; i++) { addDataPoint(values[i], mColor[i % 4], mLastValue[i], i); } } catch (ArrayIndexOutOfBoundsException e) { /* mLastValue might run into this in extreme situations */ // but then we just do not want to support more than 10 values in // our little graph } invalidate(); } private void addDataPoint(float value, final int color, final float lastValue, final int pos) { value += minValue; final Paint paint = mPaint; float newX = mLastX + mSpeed; final float v = mYOffset + value * mScaleY; paint.setColor(color); mCanvas.drawLine(mLastX, lastValue, newX, v, paint); mLastValue[pos] = v; if (pos == 0) mLastX += mSpeed; } public void setSpeed(float speed) { mSpeed = speed; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // TODO when screen size changes sometimes w or h == 0 -> Exception mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); mCanvas.setBitmap(mBitmap); mCanvas.drawColor(0xFF111111); mLastX = mWidth; // set origin to zero for (int i = 0; i < mLastValue.length; i++) mLastValue[i] = minValue; } @Override protected void onDraw(Canvas canvas) { synchronized (this) { if (mBitmap != null) { final Paint paint = mPaint; final Canvas cavas = mCanvas; if (mLastX >= mWidth) { mLastX = 0; cavas.drawColor(0xFF111111); int x = 20; paint.setColor(0x33DDFFDD); while (x < mWidth) { cavas.drawLine(x, mYOffset, x, 0, paint); x += 20; } final float v = mYOffset + minValue * mScaleY; // draw the zero line paint.setColor(0xFF779977); cavas.drawLine(0, v, mWidth, v, paint); } paint.setColor(0xaa996666); cavas.drawText(min, 1, mYOffset - 1, paint); cavas.drawText(max, 1, textHeight - 1, paint); canvas.drawBitmap(mBitmap, 0, 0, null); } } } } abstract class Visualizer extends View { Paint mPaint = new Paint(); float maxValue = 1024f; float minValue = 0f; float mScaleX; float mScaleY; float mYOffset; float mWidth; String min, max; float textWidth = 0; float textHeight = 0; public Visualizer(Context context) { super(context); } public Visualizer(Context context, AttributeSet attrs) { super(context, attrs); } public abstract void setData(float value); public abstract void setData(float[] values); public void setBoundaries(float min, float max) { this.min = String.valueOf(min); this.max = String.valueOf(max); minValue = -min; maxValue = max - min; mScaleY = -(mYOffset * (1.0f / maxValue)); mScaleX = (mWidth * (1.0f / maxValue)); float[] sizes = new float[this.max.length()]; textHeight = mPaint.getTextSize(); mPaint.getTextWidths(this.max, sizes); for (float f : sizes) textWidth += f; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mYOffset = h; mWidth = w; mScaleY = -(h * (1.0f / maxValue)); mScaleX = (w * (1.0f / maxValue)); super.onSizeChanged(w, h, oldw, oldh); } /* SIMPLE CAST FUNCTIONS */ public void setData(int value) { setData((float) value); } public void setData(double value) { setData((float) value); } public void setData(short value) { setData((float) value); } public void setData(long value) { setData((float) value); } public void setData(byte value) { setData((float) value); } public void setData(boolean value) { if (value) setData(1f); else setData(0f); } public void setData(int[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = values[i]; setData(arr); } public void setData(double[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = (float) values[i]; setData(arr); } public void setData(short[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = values[i]; setData(arr); } public void setData(long[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = values[i]; setData(arr); } public void setData(byte[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = values[i]; setData(arr); } public void setData(boolean[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = values[i] ? 1 : 0; setData(arr); } public void setData(String[] values) { final int length = values.length; float[] arr = new float[length]; for (int i = 0; i < length; i++) arr[i] = Float.valueOf(values[i]); setData(arr); } }
import android.content.Context; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; class BarsView extends Visualizer { private static final String TAG = "BarsView"; private static final int NUM_BARS = 3; private int activeBars = 0; private Bitmap mBitmap; private Canvas mCanvas = new Canvas(); private int[] mColor = new int[3]; private float barHeight; public BarsView(Context context) { super(context); init(); } public BarsView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init(){ mColor[0] = Color.argb(255, 0, 200, 0); // g mColor[1] = Color.argb(255, 200, 200, 0); // y mColor[2] = Color.argb(255, 200, 0, 0); // r activeBars = 1; } @Override public void setBoundaries(float min, float max) { super.setBoundaries(min, max); } @Override public void setData(float value) { mCanvas.drawColor(0xFF111111); updateBar(value, 0); invalidate(); } @Override public void setData(float[] values) { mCanvas.drawColor(0xFF111111); int length = values.length; if (length > activeBars){ activeBars = length; } for (int i=0; i<length; i++){ updateBar(values[i], i); } invalidate(); } private void updateBar(float value, final int pos){ value += minValue; final Paint paint = mPaint; final float v = value * mScaleX; paint.setColor(mColor[pos]); mCanvas.drawRect(minValue * mScaleX, barHeight*pos, v, barHeight*(pos+1), paint); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); barHeight = mYOffset / NUM_BARS; // TODO when screen size changes sometimes w or h == 0 -> Exception mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565); mCanvas.setBitmap(mBitmap); mCanvas.drawColor(0xFF111111); } @Override protected void onDraw(Canvas canvas) { synchronized (this) { if (mBitmap != null) { // draw bars outline final float v1 = minValue * mScaleX; final Canvas cavas = mCanvas; final Paint paint = mPaint; paint.setColor(0x44996666); for (int i=0; i<NUM_BARS;i++){ cavas.drawLine(0, barHeight*i, mWidth, barHeight*i, paint); } paint.setColor(0xaa996666); cavas.drawLine(v1, mYOffset, v1, 0, paint); cavas.drawText(min, 1, mYOffset-1, paint); cavas.drawText(max, mWidth-textWidth-1, mYOffset-1, paint); canvas.drawBitmap(mBitmap, 0, 0, null); } } } } abstract class Visualizer extends View { Paint mPaint = new Paint(); float maxValue = 1024f; float minValue = 0f; float mScaleX; float mScaleY; float mYOffset; float mWidth; String min, max; float textWidth = 0; float textHeight = 0; public Visualizer(Context context) { super(context); } public Visualizer(Context context, AttributeSet attrs) { super(context, attrs); } public abstract void setData(float value); public abstract void setData(float[] values); public void setBoundaries(float min, float max){ this.min = String.valueOf(min); this.max = String.valueOf(max); minValue = -min; maxValue = max - min; mScaleY = - (mYOffset * (1.0f / maxValue)); mScaleX = (mWidth * (1.0f / maxValue)); float[] sizes = new float[this.max.length()]; textHeight = mPaint.getTextSize(); mPaint.getTextWidths(this.max, sizes); for (float f : sizes) textWidth += f; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { mYOffset = h; mWidth = w; mScaleY = - (h * (1.0f / maxValue)); mScaleX = (w * (1.0f / maxValue)); super.onSizeChanged(w, h, oldw, oldh); } /* SIMPLE CAST FUNCTIONS */ public void setData(int value){ setData((float)value); } public void setData(double value){ setData((float)value); } public void setData(short value){ setData((float)value); } public void setData(long value){ setData((float)value); } public void setData(byte value){ setData((float)value); } public void setData(boolean value){ if (value) setData(1f); else setData(0f); } public void setData(int[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = values[i]; setData(arr); } public void setData(double[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = (float)values[i]; setData(arr); } public void setData(short[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = values[i]; setData(arr); } public void setData(long[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = values[i]; setData(arr); } public void setData(byte[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = values[i]; setData(arr); } public void setData(boolean[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = values[i] ? 1 : 0; setData(arr); } public void setData(String[] values){ final int length = values.length; float[] arr = new float[length]; for (int i=0;i<length;i++) arr[i] = Float.valueOf(values[i]); setData(arr); } }
//package apps.compass; import java.util.List; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class CompassView extends View { private float mGraduationRotateAngle = 0; private float mPointerRotateAngle = 0; private Drawable mGraduationDrawable = null; private Drawable mPointerDrawable = null; private float mGraduationDrawableRadius = 0; private float mPointerDrawableRadius = 0; private float mCanvasCenterX = 0; private float mCanvasCenterY =0; private float mPreTouchX = 0; private float mPreTouchY = 0; public CompassView(Context context) { super(context); Resources res = context.getResources(); // mGraduationDrawable = res.getDrawable(); mGraduationDrawable.setBounds(0, 0, 300, 300); // mPointerDrawable = res.getDrawable(); mPointerDrawable.setBounds(0, 0, 250, 250); mGraduationDrawableRadius = 300 / 2; mPointerDrawableRadius = 250 / 2; } public void setPointerRotateAngle(float angle) { if (angle - mPointerRotateAngle > 2 ) { while (angle - mPointerRotateAngle > 0.2) { mPointerRotateAngle += 0.2; this.invalidate(); } } else if (angle - mPointerRotateAngle < -2) { while (mPointerRotateAngle - angle > 0.2) { mPointerRotateAngle -= 0.2; this.invalidate(); } } } public void setGraduationRotateAngle(float angle) { mGraduationRotateAngle = angle; } public boolean onTouchEvent(MotionEvent event) { boolean hasRotation = false; boolean isClockwise = true; float dx = event.getX() - mPreTouchX; float dy = event.getY() - mPreTouchY; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: break; case MotionEvent.ACTION_MOVE: if (mPreTouchX > mCanvasCenterX && mPreTouchX < mCanvasCenterX + mGraduationDrawableRadius) { if (mPreTouchY > mCanvasCenterY && mPreTouchY < mCanvasCenterY + mGraduationDrawableRadius) { if (dx > 0 && dy < 0) {isClockwise = true; hasRotation = true;} else if (dx < 0 && dy > 0) {isClockwise = false; hasRotation = true;} else {hasRotation = false;} } else if (mPreTouchY > mCanvasCenterY - mGraduationDrawableRadius && mPreTouchY < mCanvasCenterY){ if (dx > 0 && dy > 0) {isClockwise = false; hasRotation = true;} else if (dx < 0 && dy < 0) {isClockwise = true; hasRotation = true;} else {hasRotation = false;} } } else if (mPreTouchX > mCanvasCenterX - mGraduationDrawableRadius && mPreTouchX < mCanvasCenterX){ if (mPreTouchY > mCanvasCenterY && mPreTouchY < mCanvasCenterY + mGraduationDrawableRadius) { if (dx > 0 && dy > 0) {isClockwise = true; hasRotation = true;} else if (dx < 0 && dy < 0) {isClockwise = false; hasRotation = true;} else {hasRotation = false;} } else if (mPreTouchY > mCanvasCenterY - mGraduationDrawableRadius && mPreTouchY < mCanvasCenterY) { if (dx > 0 && dy < 0) {isClockwise = false; hasRotation = true;} else if (dx < 0 && dy > 0) {isClockwise = true; hasRotation = true;} else {hasRotation = false;} } } break; } if (hasRotation) { float touchXToCenterX = mPreTouchX - mCanvasCenterX; float touchYToCenterY = mPreTouchY - mCanvasCenterY; float touchRadius = (float)Math.sqrt(touchXToCenterX * touchXToCenterX + touchYToCenterY * touchYToCenterY); float touchPathLen = (float) Math.sqrt(dx * dx + dy * dy); float rotateDegree = (float) Math.toDegrees(touchPathLen / touchRadius); Log.d("On Touch", "angle: "+rotateDegree); if (isClockwise) this.setGraduationRotateAngle(mGraduationRotateAngle + rotateDegree); else this.setGraduationRotateAngle(mGraduationRotateAngle - rotateDegree); this.invalidate(); } mPreTouchX = event.getX(); mPreTouchY = event.getY(); return true; } protected void onDraw(Canvas canvas) { int w = canvas.getWidth(); int h = canvas.getHeight(); mCanvasCenterX = w / 2; mCanvasCenterY = h / 2; canvas.save(); canvas.translate(mCanvasCenterX, mCanvasCenterY); canvas.rotate(-mGraduationRotateAngle); canvas.translate(-mGraduationDrawableRadius, -mGraduationDrawableRadius); mGraduationDrawable.draw(canvas); canvas.restore(); canvas.translate(mCanvasCenterX, mCanvasCenterY); canvas.rotate(-mPointerRotateAngle); canvas.translate(-mPointerDrawableRadius, -mPointerDrawableRadius); mPointerDrawable.draw(canvas); } } class Compass extends Activity { private SensorManager mSensorManager = null; private CompassView mView = null; private final SensorEventListener mSensorEventListener = new SensorEventListener() { public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void onSensorChanged(SensorEvent event) { if (mView != null) { mView.setPointerRotateAngle(event.values[0]); } } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mView = new CompassView(this); setContentView(mView); } public void onResume() { super.onResume(); List<Sensor> sensorList = mSensorManager .getSensorList(Sensor.TYPE_ORIENTATION); if (!sensorList.isEmpty()) { Sensor sensor = (Sensor) sensorList.get(0); if (sensor != null) mSensorManager.registerListener(mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_GAME); } } public void onStop() { mSensorManager.unregisterListener(mSensorEventListener); super.onStop(); } }
import java.io.File; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.hardware.SensorListener; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.View; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.drawable.Drawable; class Pint { private Drawable bgFull, bgEmpty, bgFront; private Bitmap foam; private static final float WIDTH = 320; private static final float HEIGHT = 480; private static final float TOTAL = WIDTH * HEIGHT - 50 * 320; private float currentVolume = 0; float leftY = 480, rightY = 480; float foamHeight; public Pint(Drawable bgFull, Drawable bgEmpty, Drawable bgFront, Bitmap foam) { this.bgEmpty = bgEmpty; this.bgEmpty.setBounds(0, 0, bgEmpty.getIntrinsicWidth(), bgEmpty.getIntrinsicHeight()); this.bgFull = bgFull; this.bgFull.setBounds(0, 0, bgFull.getIntrinsicWidth(), bgFull.getIntrinsicHeight()); this.bgFront = bgFront; this.bgFront.setBounds(0, 0, bgFront.getIntrinsicWidth(), bgFront.getIntrinsicHeight()); this.foam = foam; foamHeight = foam.getHeight() / 2; } private float angle = 0f; private boolean full = false; public void setAngle(float angle) { this.angle = angle; } public float getCurrentVolume() { return currentVolume; } public void setCurrentVolume(float currentVolume) { this.currentVolume = currentVolume; } public void draw(Canvas canvas) { bgEmpty.draw(canvas); canvas.save(); float emptyHeight = 0; if (!full) { currentVolume += (10 * 320); if (currentVolume > TOTAL) { full = true; } } emptyHeight = (float) (Math.tan(Math.toRadians(angle)) * WIDTH); float adjustedHeight = currentVolume / WIDTH; // normal height adjustedHeight = adjustedHeight <= 0 ? 2f : adjustedHeight; leftY = Math.max(-1000, HEIGHT - (adjustedHeight + emptyHeight)); rightY = Math.max(-1000, HEIGHT - (adjustedHeight - emptyHeight)); if (currentVolume > WIDTH) { Path p = new Path(); p.moveTo(0, HEIGHT); // lower left p.lineTo(WIDTH, HEIGHT); p.lineTo(WIDTH, rightY); p.lineTo(0, leftY); canvas.clipPath(p); bgFull.draw(canvas); canvas.restore(); canvas.drawBitmapMesh(foam, 1, 1, new float[] { 0, leftY - foamHeight, 320, rightY - foamHeight, 0, leftY + foamHeight, 320, rightY + foamHeight, }, 0, null, 0, null); } if (leftY < 5 || rightY < 5) { currentVolume *= 0.98;// -= (2000f); currentVolume -= 200f; } bgFront.draw(canvas); } } public class PintView extends View implements SensorListener { private Pint pint; private MediaPlayer mp; private Context ctx; public PintView(Context context, AttributeSet attrs) { super(context, attrs); ctx = context; SharedPreferences settings = PreferenceManager .getDefaultSharedPreferences(context); String skinName = settings.getString("skin", "Default"); loadSkin(skinName); playRefillSound(); } public PintView(Context context) { super(context); } private boolean more = true; private void playRefillSound() { mp = MediaPlayer.create(ctx, R.raw.refill);//refill.mp3 mp.start(); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); } public void loadSkin(String name) { File skinPath = new File(new File("/sdcard/ADRINK"), name); float volume = pint == null ? 0 : pint.getCurrentVolume(); pint = null; Drawable full = Drawable.createFromPath(skinPath.getAbsolutePath() + "/" + "full.png"); Drawable empty = Drawable.createFromPath(skinPath.getAbsolutePath() + "/" + "empty.png"); Drawable front = Drawable.createFromPath(skinPath.getAbsolutePath() + "/" + "front.png"); Bitmap foam = BitmapFactory.decodeFile(skinPath.getAbsolutePath() + "/" + "foam.png"); pint = new Pint(full, empty, front ,foam ); pint.setCurrentVolume(volume); } public Pint getPint() { return pint; } @Override protected void onDraw(Canvas canvas) { pint.draw(canvas); if (more) { invalidate(); } } public void setMore(boolean more) { this.more = more; } @Override public void onAccuracyChanged(int sensor, int accuracy) { // TODO Auto-generated method stub } @Override public void onSensorChanged(int sensor, float[] values) { float angle = values[2]; pint.setAngle(0 - angle); } }
package com.example.android.apis.view; // Need the following import to get access to the app resources, since this // class is in a sub-package. import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * Demonstrates making a view VISIBLE, INVISIBLE and GONE * */ public class Visibility1 extends Activity { private View mVictim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.visibility_1); // Find the view whose visibility will change mVictim = findViewById(R.id.victim); // Find our buttons Button visibleButton = (Button) findViewById(R.id.vis); Button invisibleButton = (Button) findViewById(R.id.invis); Button goneButton = (Button) findViewById(R.id.gone); // Wire each button to a click listener visibleButton.setOnClickListener(mVisibleListener); invisibleButton.setOnClickListener(mInvisibleListener); goneButton.setOnClickListener(mGoneListener); } OnClickListener mVisibleListener = new OnClickListener() { public void onClick(View v) { mVictim.setVisibility(View.VISIBLE); } }; OnClickListener mInvisibleListener = new OnClickListener() { public void onClick(View v) { mVictim.setVisibility(View.INVISIBLE); } }; OnClickListener mGoneListener = new OnClickListener() { public void onClick(View v) { mVictim.setVisibility(View.GONE); } }; } //layout/visibility_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- Demonstrates changing view visibility. See corresponding Java code. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:background="@drawable/box" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:background="@drawable/red" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/visibility_1_view_1"/> <TextView android:id="@+id/victim" android:background="@drawable/green" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/visibility_1_view_2"/> <TextView android:background="@drawable/blue" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/visibility_1_view_3"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/vis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/visibility_1_vis"/> <Button android:id="@+id/invis" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/visibility_1_invis"/> <Button android:id="@+id/gone" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/visibility_1_gone"/> </LinearLayout> </LinearLayout>
package com.example.android.apis.view; // Need the following import to get access to the app resources, since this // class is in a sub-package. import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.util.AttributeSet; import android.view.View; /** * Example of how to write a custom subclass of View. LabelView * is used to draw simple text views. Note that it does not handle * styled text or right-to-left writing systems. * */ class LabelView extends View { private Paint mTextPaint; private String mText; private int mAscent; /** * Constructor. This version is only needed if you will be instantiating * the object manually (not from a layout XML file). * @param context */ public LabelView(Context context) { super(context); initLabelView(); } /** * Construct object, initializing with any attributes we understand from a * layout file. These attributes are defined in * SDK/assets/res/any/classes.xml. * * @see android.view.View#View(android.content.Context, android.util.AttributeSet) */ public LabelView(Context context, AttributeSet attrs) { super(context, attrs); initLabelView(); CharSequence s = "LabelView_text"; if (s != null) { setText(s.toString()); } // Retrieve the color(s) to be used for this view and apply them. // Note, if you only care about supporting a single color, that you // can instead call a.getColor() and pass that to setTextColor(). setTextColor(Color.RED); int textSize =20; if (textSize > 0) { setTextSize(textSize); } } private final void initLabelView() { mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(16); mTextPaint.setColor(0xFF000000); setPadding(3, 3, 3, 3); } /** * Sets the text to display in this label * @param text The text to display. This will be drawn as one line. */ public void setText(String text) { mText = text; requestLayout(); invalidate(); } /** * Sets the text size for this label * @param size Font size */ public void setTextSize(int size) { mTextPaint.setTextSize(size); requestLayout(); invalidate(); } /** * Sets the text color for this label. * @param color ARGB value for the text */ public void setTextColor(int color) { mTextPaint.setColor(color); invalidate(); } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Determines the height of this view * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); mAscent = (int) mTextPaint.ascent(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Render the text * * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint); } } /** * Demonstrates creating a Screen that uses custom views. This example uses * {@link com.example.android.apis.view.LabelView}, which is defined in * SDK/src/com/example/android/apis/view/LabelView.java. * */ public class Test extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- Demonstrates defining custom views in a layout file. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <app.test.LabelView android:background="@drawable/icon" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Red"/> <app.test.LabelView android:background="@drawable/icon" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Blue" app:textSize="20dp"/> <app.test.LabelView android:background="@drawable/icon" android:layout_width="match_parent" android:layout_height="wrap_content" app:text="Green" app:textColor="#ffffffff" /> </LinearLayout>
package app.test; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class Test extends Activity { private static final String LOG_KEY = "Tagger"; private static Method _setTag = null; private static Method _getTag = null; static { int sdk = new Integer(Build.VERSION.SDK).intValue(); if (sdk >= 4) { try { _setTag = View.class.getMethod("setTag", new Class[] { Integer.TYPE, Object.class }); _getTag = View.class.getMethod("getTag", new Class[] { Integer.TYPE }); } catch (Throwable t) { Log.e(LOG_KEY, "Could not initialize 1.6 accessors", t); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView view = (TextView) findViewById(R.id.test); setTag(view, R.id.test, new Date()); view.setText(getTag(view, R.id.test).toString()); } public void setTag(View v, int key, Object value) { if (_setTag != null) { try { _setTag.invoke(v, key, value); } catch (Throwable t) { Log.e(LOG_KEY, "Could not use 1.6 setTag()", t); } } else { HashMap<Integer, Object> meta = (HashMap<Integer, Object>) v .getTag(); if (meta == null) { meta = new HashMap<Integer, Object>(); v.setTag(meta); } meta.put(key, value); } } public Object getTag(View v, int key) { Object result = null; if (_getTag != null) { try { result = _getTag.invoke(v, key); } catch (Throwable t) { Log.e(LOG_KEY, "Could not use 1.6 getTag()", t); } } else { HashMap<Integer, Object> meta = (HashMap<Integer, Object>) v .getTag(); if (meta == null) { meta = new HashMap<Integer, Object>(); v.setTag(meta); } result = meta.get(key); } return (result); } } //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:id="@+id/test" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
package app.test; import java.util.Random; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; public class Test extends Activity { class RenderView extends View { Random rand = new Random(); public RenderView(Context context) { super(context); } protected void onDraw(Canvas canvas) { canvas.drawRGB(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)); invalidate(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(new RenderView(this)); } }
package app.test; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.util.AttributeSet; import android.view.View; class CompassView extends View { private Paint markerPaint; private Paint textPaint; private Paint circlePaint; private String northString; private String eastString; private String southString; private String westString; private int textHeight; public void setBearing(float _bearing) { bearing = _bearing; } public float getBearing() { return bearing; } private float bearing; public CompassView(Context context) { super(context); initCompassView(); } public CompassView(Context context, AttributeSet attrs) { super(context, attrs); initCompassView(); } public CompassView(Context context, AttributeSet attrs, int defaultStyle) { super(context, attrs, defaultStyle); initCompassView(); } protected void initCompassView() { setFocusable(true); Resources r = this.getResources(); northString = "North"; eastString = "East"; southString = "South"; westString = "West"; circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG); circlePaint.setColor(Color.BLACK); circlePaint.setStrokeWidth(1); circlePaint.setStyle(Paint.Style.FILL_AND_STROKE); markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); markerPaint.setColor(Color.RED); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(Color.BLACK); textHeight = (int) textPaint.measureText("yY"); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = measure(widthMeasureSpec); int measuredHeight = measure(heightMeasureSpec); int d = Math.min(measuredWidth, measuredHeight); setMeasuredDimension(d, d); } private int measure(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.UNSPECIFIED) { result = 200; } else { result = specSize; } return result; } @Override protected void onDraw(Canvas canvas) { int px = getMeasuredWidth() / 2; int py = getMeasuredHeight() / 2; int radius = Math.min(px, py); canvas.drawCircle(px, py, radius, circlePaint); canvas.save(); canvas.rotate(-bearing, px, py); int textWidth = (int) textPaint.measureText("W"); int cardinalX = px - textWidth / 2; int cardinalY = py - radius + textHeight; for (int i = 0; i < 24; i++) { canvas.drawLine(px, py - radius, px, py - radius + 10, markerPaint); canvas.save(); canvas.translate(0, textHeight); if (i % 6 == 0) { String dirString = ""; switch (i) { case (0): { dirString = northString; int arrowY = 2 * textHeight; canvas.drawLine(px, arrowY, px - 5, 3 * textHeight, markerPaint); canvas.drawLine(px, arrowY, px + 5, 3 * textHeight, markerPaint); break; } case (6): dirString = eastString; break; case (12): dirString = southString; break; case (18): dirString = westString; break; } canvas.drawText(dirString, cardinalX, cardinalY, textPaint); } else if (i % 3 == 0) { String angle = String.valueOf(i * 15); float angleTextWidth = textPaint.measureText(angle); int angleTextX = (int) (px - angleTextWidth / 2); int angleTextY = py - radius + textHeight; canvas.drawText(angle, angleTextX, angleTextY, textPaint); } canvas.restore(); canvas.rotate(15, px, py); } canvas.restore(); } } public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); CompassView cv = (CompassView) this.findViewById(R.id.compassView); cv.setBearing(45); } } //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"> <app.test.CompassView android:id="@+id/compassView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
package app.test; // Need the following import to get access to the app resources, since this // class is in a sub-package. //import com.example.android.apis.R; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Picture; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; public class Test extends GraphicsActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new SampleView(this)); } private static class SampleView extends View { private Paint[] mPaints; private Paint mFramePaint; private boolean[] mUseCenters; private RectF[] mOvals; private RectF mBigOval; private float mStart; private float mSweep; private int mBigIndex; private static final float SWEEP_INC = 2; private static final float START_INC = 15; public SampleView(Context context) { super(context); mPaints = new Paint[4]; mUseCenters = new boolean[4]; mOvals = new RectF[4]; mPaints[0] = new Paint(); mPaints[0].setAntiAlias(true); mPaints[0].setStyle(Paint.Style.FILL); mPaints[0].setColor(0x88FF0000); mUseCenters[0] = false; mPaints[1] = new Paint(mPaints[0]); mPaints[1].setColor(0x8800FF00); mUseCenters[1] = true; mPaints[2] = new Paint(mPaints[0]); mPaints[2].setStyle(Paint.Style.STROKE); mPaints[2].setStrokeWidth(4); mPaints[2].setColor(0x880000FF); mUseCenters[2] = false; mPaints[3] = new Paint(mPaints[2]); mPaints[3].setColor(0x88888888); mUseCenters[3] = true; mBigOval = new RectF(40, 10, 280, 250); mOvals[0] = new RectF( 10, 270, 70, 330); mOvals[1] = new RectF( 90, 270, 150, 330); mOvals[2] = new RectF(170, 270, 230, 330); mOvals[3] = new RectF(250, 270, 310, 330); mFramePaint = new Paint(); mFramePaint.setAntiAlias(true); mFramePaint.setStyle(Paint.Style.STROKE); mFramePaint.setStrokeWidth(0); } private void drawArcs(Canvas canvas, RectF oval, boolean useCenter, Paint paint) { canvas.drawRect(oval, mFramePaint); canvas.drawArc(oval, mStart, mSweep, useCenter, paint); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); drawArcs(canvas, mBigOval, mUseCenters[mBigIndex], mPaints[mBigIndex]); for (int i = 0; i < 4; i++) { drawArcs(canvas, mOvals[i], mUseCenters[i], mPaints[i]); } mSweep += SWEEP_INC; if (mSweep > 360) { mSweep -= 360; mStart += START_INC; if (mStart >= 360) { mStart -= 360; } mBigIndex = (mBigIndex + 1) % mOvals.length; } invalidate(); } } } 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()); } } } }
package app.Test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.os.Bundle; import android.view.View; public class appTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicsView(this)); } static public class GraphicsView extends View { private static final String QUOTE = "This is a test. This is a demo."; private Path circle; private Paint cPaint; private Paint tPaint; public GraphicsView(Context context) { super(context); int color = getResources().getColor(R.color.mycolor); circle = new Path(); circle.addCircle(150, 150, 100, Direction.CW); cPaint = new Paint(Paint.ANTI_ALIAS_FLAG); cPaint.setStyle(Paint.Style.STROKE); cPaint.setColor(Color.LTGRAY); cPaint.setStrokeWidth(3); setBackgroundResource(R.drawable.icon); tPaint = new Paint(Paint.ANTI_ALIAS_FLAG); tPaint.setStyle(Paint.Style.FILL_AND_STROKE); tPaint.setColor(Color.BLACK); tPaint.setTextSize(20f); setBackgroundColor(color); } @Override protected void onDraw(Canvas canvas) { canvas.drawTextOnPath(QUOTE, circle, 0, 20, tPaint); } } } //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" android:background="@drawable/icon"> <org.example.graphics.Graphics.GraphicsView android:id="@+id/graphics" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Graphics</string> </resources> //colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="mycolor">#7fff00ff</color> </resources>
package app.Test; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Path.Direction; import android.os.Bundle; import android.view.View; public class appTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new GraphicsView(this)); } static public class GraphicsView extends View { private static final String QUOTE = "This is a test. This is a demo."; private Path circle; private Paint cPaint; private Paint tPaint; public GraphicsView(Context context) { super(context); int color = Color.BLUE; circle = new Path(); circle.addCircle(150, 150, 100, Direction.CW); cPaint = new Paint(Paint.ANTI_ALIAS_FLAG); cPaint.setStyle(Paint.Style.STROKE); cPaint.setColor(Color.LTGRAY); cPaint.setStrokeWidth(3); setBackgroundResource(R.drawable.icon); } @Override protected void onDraw(Canvas canvas) { canvas.drawPath(circle, cPaint); } } } //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" android:background="@drawable/icon"> <org.example.graphics.Graphics.GraphicsView android:id="@+id/graphics" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Graphics</string> </resources> //colors.xml <?xml version="1.0" encoding="utf-8"?> <resources> <color name="mycolor">#7fff00ff</color> </resources>
12-WebView
package app.Test; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; public class appTest extends Activity { private EditText urlText; private Button goButton; private WebView webView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); urlText = (EditText) findViewById(R.id.url_field); goButton = (Button) findViewById(R.id.go_button); webView = (WebView) findViewById(R.id.web_view); goButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { openBrowser(); } }); urlText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { openBrowser(); return true; } return false; } }); } /** Open a browser on the URL specified in the text box */ private void openBrowser() { webView.loadUrl(urlText.getText().toString()); webView.requestFocus(); } } //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"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/url_field" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:lines="1" /> <Button android:id="@+id/go_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/go_button" /> </LinearLayout> <WebView android:id="@+id/web_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1.0" /> </LinearLayout>
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import com.example.android.apis.R; /** * Sample creating 10 webviews. */ public class WebView1 extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.webview_1); final String mimeType = "text/html"; final String encoding = "utf-8"; WebView wv; wv = (WebView) findViewById(R.id.wv1); wv.loadData("<a href='x'>Hello World! - 1</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv2); wv.loadData("<a href='x'>Hello World! - 2</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv3); wv.loadData("<a href='x'>Hello World! - 3</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv4); wv.loadData("<a href='x'>Hello World! - 4</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv5); wv.loadData("<a href='x'>Hello World! - 5</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv6); wv.loadData("<a href='x'>Hello World! - 6</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv7); wv.loadData("<a href='x'>Hello World! - 7</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv8); wv.loadData("<a href='x'>Hello World! - 8</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv9); wv.loadData("<a href='x'>Hello World! - 9</a>", mimeType, encoding); wv = (WebView) findViewById(R.id.wv10); wv.loadData("<a href='x'>Hello World! - 10</a>", mimeType, encoding); } } //layout/webview_1.xml <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <WebView android:id="@+id/wv1" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv2" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv3" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv4" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv5" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv6" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv7" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv8" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv9" android:layout_height="wrap_content" android:layout_width="match_parent" /> <WebView android:id="@+id/wv10" android:layout_height="wrap_content" android:layout_width="match_parent" /> </LinearLayout> </ScrollView>
Add a client to the web view
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); // webview.setWebViewClient(new WebViewClient()); webview.loadUrl("http://www.google.com"); setContentView(webview); } }
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView wv = (WebView) findViewById(R.id.webview1); wv.setWebViewClient(new Callback()); WebSettings webSettings = wv.getSettings(); webSettings.setBuiltInZoomControls(true); wv.loadUrl("http://yourHost.com/1.jpg"); } private class Callback extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return(false); } } } //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" > <WebView android:id="@+id/webview1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView wv = (WebView) findViewById(R.id.webview1); wv.loadUrl("http://www.google.com"); } private class Callback extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return(false); } } } //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" > <WebView android:id="@+id/webview1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView wv = (WebView) findViewById(R.id.webview1); wv.loadUrl("file:///android_asset/Index.html"); } private class Callback extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return(false); } } } //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" > <WebView android:id="@+id/webview1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package com.commonsware.android.browser2; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class BrowserDemo2 extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); browser.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8"); } } //res\layout\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" > <WebView android:id="@+id/webkit" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> Load static html with Javascript package com.commonsware.android.webkit; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.Date; public class BrowserDemo3 extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); browser.setWebViewClient(new Callback()); loadTime(); } void loadTime() { String page="<html><body><a href=\"clock\">" +new Date().toString() +"</a></body></html>"; browser.loadDataWithBaseURL("x-data://base", page, "text/html", "UTF-8", null); } private class Callback extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { loadTime(); return(true); } } } //res\layout\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" > <WebView android:id="@+id/webkit" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
package com.commonsware.android.browser1; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class BrowserDemo1 extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); browser=(WebView)findViewById(R.id.webkit); browser.loadUrl("http://commonsware.com"); } } //res\layout\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" > <WebView android:id="@+id/webkit" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
package app.test; import android.app.Activity; import android.os.Bundle; import android.net.Uri; import android.text.TextUtils; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); // Add a client to the view webview.setWebViewClient(mClient); webview.loadUrl("http://www.google.com"); setContentView(webview); } private WebViewClient mClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri request = Uri.parse(url); if (TextUtils.equals(request.getAuthority(), "www.google.com")) { // Allow the load return false; } Toast.makeText(Test.this, "Sorry, buddy", Toast.LENGTH_SHORT) .show(); return true; } }; }
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl("http://www.google.com/"); setContentView(webview); } }
package app.test; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); WebView upperView = (WebView)findViewById(R.id.upperview); upperView.getSettings().setBuiltInZoomControls(true); upperView.loadUrl("file:///android_asset/android.jpg"); WebView lowerView = (WebView)findViewById(R.id.lowerview); String htmlString = "<h1>Header</h1><p>This is HTML text<br /><i>Formatted in italics</i></p>"; lowerView.loadData(htmlString, "text/html", "utf-8"); } } //main.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="fill_parent" android:orientation="vertical"> <WebView android:id="@+id/upperview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <WebView android:id="@+id/lowerview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout>
13-Toast
Raise a Toast
package app.test; import android.app.Activity; import android.os.Bundle; import android.net.Uri; import android.text.TextUtils; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); webview.getSettings().setJavaScriptEnabled(true); // Add a client to the view webview.setWebViewClient(mClient); webview.loadUrl("http://www.google.com"); setContentView(webview); } private WebViewClient mClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri request = Uri.parse(url); if (TextUtils.equals(request.getAuthority(), "www.google.com")) { // Allow the load return false; } Toast.makeText(Test.this, "Sorry, buddy", Toast.LENGTH_SHORT) .show(); return true; } }; } /*<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <form name="input" action="form.html" method="get"> Enter Email: <input type="text" id="emailAddress" /> <input type="submit" value="Submit" /> </form> </html>*/
Popup Debug Message
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.widget.Toast; // Classe d'utilitaires abstract class Utils { public static void popDebug(Context context, String message) { Toast.makeText(context, message, 1000).show(); } }
package ch.dissem.android.utils; import android.content.Context; import android.os.Handler; import android.widget.Toast; /** * @author christian * */ public class ThreadingUtils { public static void showToast(Handler handler, final Context context, final int resId, final int duration) { handler.post(new Runnable() { public void run() { Toast.makeText(context, resId, duration).show(); } }); } }
import android.content.Context; import android.content.res.Resources; import android.widget.Toast; /** * The Toast util class * @author pangsy * @createDate 2011-7-1 * @version v0.1 */ public final class ToastUtil { /** * Toast the long text * @param context * @param text */ public static void ToastLong(Context context, String text) { Toast.makeText(context, text, Toast.LENGTH_LONG).show(); } /** * Toast the long text * @param context * @param resId */ public static void ToastLong(Context context, int resId) { Resources res = context.getResources(); Toast.makeText(context, res.getString(resId), Toast.LENGTH_LONG).show(); } /** * Toast the short text * @param context * @param resId */ public static void ToastShort(Context context, int resId) { Resources res = context.getResources(); Toast.makeText(context, res.getString(resId), Toast.LENGTH_SHORT).show(); } /** * Toast the short text * @param context * @param text */ public static void ToastShort(Context context, String text) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } }
Show long,short Toast
//package com.retain; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.Date; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.ImageView; import android.widget.Toast; /** * @author Nazmul Idris * @version 1.0 * @since Jul 8, 2008, 2:35:39 PM */ class AppUtils { /** * 127.0.0.1 in the emulator points back to itself. Use this if you want to * access your host OS */ public static String EmulatorLocalhost = "10.0.2.2"; /** * shows a short message on top of your app... it goes away automatically * after a short delay */ public static void showToastShort(Context a, String msg) { Toast.makeText(a, msg, Toast.LENGTH_SHORT).show(); } /** * shows a short message on top of your app... it goes away automatically * after a long delay */ public static void showToastLong(Context a, String msg) { Toast.makeText(a, msg, Toast.LENGTH_LONG).show(); } public static void showToast(Context a, String msg, int length) { Toast.makeText(a, msg, length).show(); } }// end class AppUtils
AlertDialog vs Toast
//package com.jwetherell.pedometer.utilities; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.view.Gravity; import android.widget.Toast; abstract class MessageUtilities { public static enum ConfirmationResult {YES,NO}; public static void confirmUser( Context context, String msg, DialogInterface.OnClickListener yesClick, DialogInterface.OnClickListener noClick){ Builder alert = new AlertDialog.Builder(context); alert.setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Confirmation") .setMessage(msg) .setPositiveButton( "Yes", yesClick) .setNegativeButton("No", noClick) .show(); } public static void helpUser(Context context, String msg) { Toast t = Toast.makeText(context, msg, Toast.LENGTH_LONG); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } public static void alertUser(Context context, String msg) { Toast t = Toast.makeText(context, msg, Toast.LENGTH_SHORT); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } public static void alertUserTop(Context context, String msg) { Toast t = Toast.makeText(context, msg, Toast.LENGTH_SHORT); t.setGravity(Gravity.TOP, 0, 0); t.show(); } }
Toast.LENGTH_SHORT
import android.content.Context; import android.widget.Toast; /** * @author Denis Migol * */ class ToastUtil { private ToastUtil() { } public static void showText(final Context context, final String text) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } public static void showNotImplemented(final Context context) { showText(context, "Not yet implemented"); } }
Responsible for sending Toasts under all circumstances.
//package org.acra.util; import android.content.Context; import android.util.Log; import android.widget.Toast; /** * Responsible for sending Toasts under all circumstances. * <p/> * @author William Ferguson * @since 4.3.0 */ public final class ToastSender { /** * Sends a Toast and ensures that any Exception thrown during sending is handled. * * @param context Application context. * @param toastResourceId Id of the resource to send as the Toast message. * @param toastLength Length of the Toast. */ public static void sendToast(Context context, int toastResourceId, int toastLength) { try { Toast.makeText(context, toastResourceId, toastLength).show(); } catch (RuntimeException e) { // Log.e(ACRA.LOG_TAG, "Could not send crash Toast", e); } } }
//package djrain.lib; import android.content.Context; import android.widget.Toast; public class ToastEx { private static Toast showing; // public static void makeText(Context context, String text) // { // if (showing != null) // { // showing.cancel(); // showing = null; // } // showing = Toast.makeText(context, text, Toast.LENGTH_SHORT); // showing.show(); // } public static void makeText(Context context, String text) { if (showing == null) { showing = Toast.makeText(context, text, Toast.LENGTH_SHORT); } else { showing.setText(text); } showing.show(); } }
import android.content.Context; import android.os.Vibrator; import android.widget.Toast; class Util { public static Toast toast; private static String lastToastText; public static void showToast(Context _context, String _text) { if (toast != null) { toast.cancel(); } if (_text != null && _text.equals(lastToastText)) { toast.show(); } else { lastToastText = _text; toast = Toast.makeText(_context, _text, Toast.LENGTH_SHORT); toast.show(); } } }
Toast and Notification, vibrate and sound
package app.test; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; class ActivityToast extends Activity { OnClickListener listener1 = null; OnClickListener listener2 = null; Button button1; Button button2; private static int NOTIFICATIONS_ID = R.layout.activity_toast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listener1 = new OnClickListener() { public void onClick(View v) { setTitle("Toast"); showToast(Toast.LENGTH_SHORT); } }; listener2 = new OnClickListener() { public void onClick(View v) { setTitle("Toast"); showToast(Toast.LENGTH_LONG); showNotification(); } }; setContentView(R.layout.activity_toast); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(listener1); button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(listener2); } protected void showToast(int type) { View view = inflateView(R.layout.toast); TextView tv = (TextView) view.findViewById(R.id.content); tv.setText("aaa"); Toast toast = new Toast(this); toast.setView(view); toast.setDuration(type); toast.show(); } private View inflateView(int resource) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); return vi.inflate(resource, null); } protected void showNotification() { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); CharSequence title = "asdf"; CharSequence contents = "yourHost.com"; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ActivityMain.class), 0); Notification notification = new Notification(R.drawable.icon, title, System.currentTimeMillis()); notification.setLatestEventInfo(this, title, contents, contentIntent); notification.vibrate = new long[] { 100, 250, 100, 500 }; notificationManager.notify(NOTIFICATIONS_ID, notification); } } class ActivityMainNotification extends Activity { private static int NOTIFICATIONS_ID = R.layout.activity_notification; private NotificationManager mNotificationManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); Button button; mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); button = (Button) findViewById(R.id.sun_1); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setWeather("A", "B", "C", R.drawable.sun); } }); button = (Button) findViewById(R.id.cloudy_1); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setWeather("A", "B", "C", R.drawable.cloudy); } }); button = (Button) findViewById(R.id.rain_1); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setWeather("A", "B", "C", R.drawable.rain); } }); button = (Button) findViewById(R.id.defaultSound); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setDefault(Notification.DEFAULT_SOUND); } }); button = (Button) findViewById(R.id.defaultVibrate); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setDefault(Notification.DEFAULT_VIBRATE); } }); button = (Button) findViewById(R.id.defaultAll); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { setDefault(Notification.DEFAULT_ALL); } }); button = (Button) findViewById(R.id.clear); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mNotificationManager.cancel(NOTIFICATIONS_ID); } }); } private void setWeather(String tickerText, String title, String content, int drawable) { Notification notification = new Notification(drawable, tickerText, System.currentTimeMillis()); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ActivityMain.class), 0); notification.setLatestEventInfo(this, title, content, contentIntent); mNotificationManager.notify(NOTIFICATIONS_ID, notification); } private void setDefault(int defaults) { PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ActivityMain.class), 0); String title = "t"; String content = "c"; final Notification notification = new Notification(R.drawable.sun, content, System.currentTimeMillis()); notification.setLatestEventInfo(this, title, content, contentIntent); notification.defaults = defaults; mNotificationManager.notify(NOTIFICATIONS_ID, notification); } } public class ActivityMain extends Activity { OnClickListener listener1 = null; OnClickListener listener2 = null; Button button1; Button button2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listener1 = new OnClickListener() { public void onClick(View v) { setTitle("Notification"); Intent intent = new Intent(ActivityMain.this, ActivityMainNotification.class); startActivity(intent); } }; listener2 = new OnClickListener() { public void onClick(View v) { setTitle("Toast"); Intent intent = new Intent(ActivityMain.this, ActivityToast.class); startActivity(intent); } }; setContentView(R.layout.main); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(listener1); button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(listener2); } } //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"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Notification" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Toast" /> </LinearLayout> //toast.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:drawable/toast_frame"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/default_icon" /> <TextView android:id="@+id/content" android:layout_gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="6dip" /> </LinearLayout> </FrameLayout> //activity_toast.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"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Short Toast" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Long Toast" /> </LinearLayout> //activity_notification.xml <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/sun_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="A" /> <Button android:id="@+id/cloudy_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="B" /> <Button android:id="@+id/rain_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:text="Advanced notification" /> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/defaultSound" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sound notification" /> <Button android:id="@+id/defaultVibrate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Vibarate notification" /> <Button android:id="@+id/defaultAll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Vibrate and Sound notification" /> </LinearLayout> <Button android:id="@+id/clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dip" android:text="Remove notification" /> </LinearLayout> </ScrollView>
Using Toast.LENGTH_SHORT
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; import android.widget.ToggleButton; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btnOpen = (Button) findViewById(R.id.btnOpen); btnOpen.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String str = "You have clicked the Open button"; DisplayToast(str); } }); Button btnSave = (Button) findViewById(R.id.btnSave); btnSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { DisplayToast("You have clicked the Save button"); } }); CheckBox checkBox = (CheckBox) findViewById(R.id.chkAutosave); checkBox.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (((CheckBox) v).isChecked()) DisplayToast("CheckBox is checked"); else DisplayToast("CheckBox is unchecked"); } }); RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rdbGp1); radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton rb1 = (RadioButton) findViewById(R.id.rdb1); if (rb1.isChecked()) { DisplayToast("Option 1 checked!"); } else { DisplayToast("Option 2 checked!"); } } }); ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle1); toggleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (((ToggleButton) v).isChecked()) DisplayToast("Toggle button is On"); else DisplayToast("Toggle button is Off"); } }); } private void DisplayToast(String msg) { Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).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="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/btnSave" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> <Button android:id="@+id/btnOpen" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open" /> <ImageButton android:id="@+id/btnImg1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/icon" /> <EditText android:id="@+id/txtName" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/chkAutosave" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Autosave" /> <CheckBox android:id="@+id/star" style="?android:attr/starStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioGroup android:id="@+id/rdbGp1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <RadioButton android:id="@+id/rdb1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Option 1" /> <RadioButton android:id="@+id/rdb2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Option 2" /> </RadioGroup> <ToggleButton android:id="@+id/toggle1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
package com.commonsware.android.messages; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MessageDemo extends Activity implements View.OnClickListener { Button alert; Button toast; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); alert=(Button)findViewById(R.id.alert); alert.setOnClickListener(this); toast=(Button)findViewById(R.id.toast); toast.setOnClickListener(this); } public void onClick(View view) { if (view==alert) { new AlertDialog.Builder(this) .setTitle("MessageDemo") .setMessage("eek!") .setNeutralButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dlg, int sumthin) { // do nothing -- it will close on its own } }) .show(); } else { Toast .makeText(this, "<clink, clink>", Toast.LENGTH_SHORT) .show(); } } } //res\layout\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" > <Button android:id="@+id/alert" android:text="Raise an alert" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/toast" android:text="Make a toast" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout>
14-TableLayout
Switch to a TableLayout
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //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" android:stretchColumns="1" > <TableRow> <TextView android:text="Name:" /> <EditText android:id="@+id/name" /> </TableRow> <TableRow> <TextView android:text="Address:" /> <EditText android:id="@+id/addr" /> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; /** * <p>This example shows how to use horizontal gravity in a table layout.</p> */ public class TableLayout11 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_11); } } //layout/table_layout_11.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1"> <TableRow> <TextView android:layout_column="1" android:text="@string/table_layout_7_open" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="@string/table_layout_7_save" android:background="#FF00FF00" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <!-- Horizontally centers the content of the cell --> <TextView android:layout_column="1" android:text="@string/table_layout_7_save_as" android:background="#FFFF0000" android:layout_gravity="center_horizontal" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_save_as_shortcut" android:background="#FFFF00FF" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="@string/table_layout_7_x" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_import" android:padding="3dip" /> </TableRow> <TableRow> <View android:layout_height="68dip" android:background="#FF909090" /> <!-- Aligns the content of the cell to the bottom right --> <TextView android:text="@string/table_layout_7_export" android:background="#FFFF0000" android:layout_gravity="right|bottom" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_export_shortcut" android:background="#FF00FFFF" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class TableLayout4 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_4); } } //layout/table_layout_4.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- Stretch some columns --> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="@string/table_layout_4_open" android:padding="3dip" /> <TextView android:text="@string/table_layout_4_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_4_save" android:padding="3dip" /> <TextView android:text="@string/table_layout_4_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> </TableLayout>
Table layout demo
package app.test; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.RelativeLayout; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);; setContentView(R.layout.main); } } //main.xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="UserName:" android:textStyle="bold" android:gravity="right" android:padding="3dip" /> <EditText android:id="@+id/username" android:padding="3dip" android:scrollHorizontally="true" /> </TableRow> <TableRow> <TextView android:text="Password:" android:textStyle="bold" android:gravity="right" android:padding="3dip" /> <EditText android:id="@+id/password" android:password="true" android:padding="3dip" android:scrollHorizontally="true" /> </TableRow> <TableRow android:gravity="right"> <Button android:id="@+id/cancel" android:text="Cancel" /> <Button android:id="@+id/login" android:text="Login" /> </TableRow> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.widget.TableLayout; import android.widget.Button; import android.os.Bundle; import android.view.View; public class TableLayout9 extends Activity { private boolean mShrink; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_9); final TableLayout table = (TableLayout) findViewById(R.id.menu); Button button = (Button) findViewById(R.id.toggle); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mShrink = !mShrink; table.setColumnShrinkable(0, mShrink); } }); mShrink = table.isColumnShrinkable(0); } } //layout/table_layout_9.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TableLayout android:id="@+id/menu" android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:text="@string/table_layout_9_open" android:padding="3dip" /> <TextView android:text="@string/table_layout_9_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_9_save" android:padding="3dip" /> <TextView android:text="@string/table_layout_9_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_9_save_as" android:padding="3dip" /> <TextView android:text="@string/table_layout_9_save_as_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_9_save_all" android:padding="3dip" /> <TextView android:text="@string/table_layout_9_save_all_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_9_import" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_9_export" android:padding="3dip" /> <TextView android:text="@string/table_layout_9_export_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> </TableLayout> <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/table_layout_9_toggle_shrink" /> </LinearLayout> </ScrollView>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.widget.TableLayout; import android.widget.Button; import android.widget.TableRow; import android.widget.TextView; import android.os.Bundle; import android.view.Gravity; import android.view.View; public class TableLayout8 extends Activity { private boolean mStretch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_8); final TableLayout table = (TableLayout) findViewById(R.id.menu); Button button = (Button) findViewById(R.id.toggle); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mStretch = !mStretch; table.setColumnStretchable(1, mStretch); } }); mStretch = table.isColumnStretchable(1); appendRow(table); } private void appendRow(TableLayout table) { TableRow row = new TableRow(this); TextView label = new TextView(this); label.setText(R.string.table_layout_8_quit); label.setPadding(3, 3, 3, 3); TextView shortcut = new TextView(this); shortcut.setText(R.string.table_layout_8_ctrlq); shortcut.setPadding(3, 3, 3, 3); shortcut.setGravity(Gravity.RIGHT | Gravity.TOP); row.addView(label, new TableRow.LayoutParams(1)); row.addView(shortcut, new TableRow.LayoutParams()); table.addView(row, new TableLayout.LayoutParams()); } } //layout.table_layout_8.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TableLayout android:id="@+id/menu" android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:layout_column="1" android:text="table_layout_8_open" android:padding="3dip" /> <TextView android:text="table_layout_8_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="table_layout_8_save" android:padding="3dip" /> <TextView android:text="table_layout_8_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="table_layout_8_save_as" android:padding="3dip" /> <TextView android:text="table_layout_8_save_as_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_8_x" android:padding="3dip" /> <TextView android:text="table_layout_8_import" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_8_x" android:padding="3dip" /> <TextView android:text="table_layout_8_export" android:padding="3dip" /> <TextView android:text="table_layout_8_export_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> </TableLayout> <Button android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="table_layout_8_toggle_stretch" /> </LinearLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class TableLayout7 extends Activity { private boolean mShortcutsCollapsed; private boolean mCheckmarksCollapsed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_7); final TableLayout table = (TableLayout) findViewById(R.id.menu); Button button = (Button) findViewById(R.id.toggle1); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mShortcutsCollapsed = !mShortcutsCollapsed; table.setColumnCollapsed(2, mShortcutsCollapsed); } }); button = (Button) findViewById(R.id.toggle2); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mCheckmarksCollapsed = !mCheckmarksCollapsed; table.setColumnCollapsed(0, mCheckmarksCollapsed); } }); mCheckmarksCollapsed = table.isColumnCollapsed(0); mShortcutsCollapsed = table.isColumnCollapsed(2); appendRow(table); } private void appendRow(TableLayout table) { TableRow row = new TableRow(this); TextView label = new TextView(this); label.setText(R.string.table_layout_7_quit); label.setPadding(3, 3, 3, 3); TextView shortcut = new TextView(this); shortcut.setText(R.string.table_layout_7_ctrlq); shortcut.setPadding(3, 3, 3, 3); shortcut.setGravity(Gravity.RIGHT | Gravity.TOP); row.addView(label, new TableRow.LayoutParams(1)); row.addView(shortcut, new TableRow.LayoutParams()); table.addView(row, new TableLayout.LayoutParams()); } } //layout/table_layout_7.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TableLayout android:id="@+id/menu" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1" android:collapseColumns="2"> <TableRow> <TextView android:layout_column="1" android:text="@string/table_layout_7_open" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="@string/table_layout_7_save" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:layout_column="1" android:text="@string/table_layout_7_save_as" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_save_as_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="@string/table_layout_7_x" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_import" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_7_x" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_export" android:padding="3dip" /> <TextView android:text="@string/table_layout_7_export_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> </TableLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/toggle2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/table_layout_7_toggle_checkmarks" /> <Button android:id="@+id/toggle1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/table_layout_7_toggle_shortcuts" /> </LinearLayout> </LinearLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class TableLayout5 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_5); } } //layout/table_layout_5.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <!-- Stretch some columns --> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="table_layout_5_open" android:padding="3dip" /> <TextView android:text="table_layout_5_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_5_save" android:padding="3dip" /> <TextView android:text="table_layout_5_save_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_5_save_as" android:padding="3dip" /> <TextView android:text="table_layout_5_save_as_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="table_layout_5_import" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_5_export" android:padding="3dip" /> <TextView android:text="table_layout_5_export_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <View android:layout_height="2dip" android:background="#FF909090" /> <TableRow> <TextView android:text="table_layout_5_quit" android:padding="3dip" /> </TableRow> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class TableLayout2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_2); } } //layout/table_layout_2.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TableRow> <Button android:text="table_layout_2_open" /> <TextView android:text="table_layout_2_path_1" android:padding="3dip" /> </TableRow> <TableRow> <Button android:text="table_layout_2_save_all"/> </TableRow> <TableRow> <Button android:text="table_layout_2_save" android:visibility="invisible" /> <TextView android:text="table_layout_2_path_2" android:padding="3dip" /> </TableRow> </TableLayout>
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class TableLayout1 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.table_layout_1); } } //layout/table_layout_1.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2007 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. --> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TableRow> <TextView android:text="table_layout_1_star" android:padding="3dip" /> <TextView android:text="table_layout_1_open" android:padding="3dip" /> <TextView android:text="table_layout_1_open_shortcut" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_1_triple_star" android:padding="3dip" /> <TextView android:text="table_layout_1_save" android:padding="3dip" /> <TextView android:text="table_layout_1_save_shortcut" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="table_layout_1_star" android:padding="3dip" /> <TextView android:text="table_layout_1_quit" android:padding="3dip" /> <TextView android:text="table_layout_1_quit_shortcut" android:padding="3dip" /> </TableRow> </TableLayout>
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //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" android:stretchColumns="0,1,2" > <EditText android:text="Fullname:" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TableRow> <TextView android:text="Edgar" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Allen" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Poe" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </TableRow> </TableLayout>
Using TableLayout and TableRow to display color
package app.test; import android.app.Activity; import android.os.Bundle; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); } } <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="0"> <TableRow> <View android:layout_height="80px" android:background="#000000"/> <TextView android:text="#000000" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#440000" /> <TextView android:text="#440000" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#884400" /> <TextView android:text="#884400" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#aa8844" /> <TextView android:text="#aa8844" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffaa88" /> <TextView android:text="#ffaa88" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffffaa" /> <TextView android:text="#ffffaa" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> <TableRow> <View android:layout_height="80px" android:background="#ffffff" /> <TextView android:text="#ffffff" android:paddingLeft="4px" android:layout_gravity="center_vertical" /> </TableRow> </TableLayout> </ScrollView>
15-EditText
Use EditText to accept user input
package app.Test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.Button; import android.widget.EditText; public class appTest extends Activity { private EditText urlText; private Button goButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get a handle to all user interface elements urlText = (EditText) findViewById(R.id.url_field); goButton = (Button) findViewById(R.id.go_button); // Setup event handlers goButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { openBrowser(); } }); urlText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { openBrowser(); return true; } return false; } }); } /** Open a browser on the URL specified in the text box */ private void openBrowser() { Uri uri = Uri.parse(urlText.getText().toString()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } } //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"> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/url_field" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:lines="1" /> <Button android:id="@+id/go_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/go_button" /> </LinearLayout> <WebView android:id="@+id/web_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1.0" /> </LinearLayout>
Create Edit Text
//package com.akjava.lib.android.ui; import java.io.BufferedInputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; class WidgetUtil { public static EditText createEditText(Context context){ return createEditText(context,""); } public static EditText createEditText(Context context,String text){ EditText bt=new EditText(context); bt.setText(text); return bt; } }
package com.example.android.notepad; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; /** * This Activity handles "editing" a note, where editing is responding to * {@link Intent#ACTION_VIEW} (request to view data), edit a note * {@link Intent#ACTION_EDIT}, create a note {@link Intent#ACTION_INSERT}, or * create a new note from the current contents of the clipboard {@link Intent#ACTION_PASTE}. * * NOTE: Notice that the provider operations in this Activity are taking place on the UI thread. * This is not a good practice. It is only done here to make the code more readable. A real * application should use the {@link android.content.AsyncQueryHandler} * or {@link android.os.AsyncTask} object to perform operations asynchronously on a separate thread. */ public class NoteEditor extends Activity { // For logging and debugging purposes private static final String TAG = "NoteEditor"; /* * Creates a projection that returns the note ID and the note contents. */ private static final String[] PROJECTION = new String[] { NotePad.Notes._ID, NotePad.Notes.COLUMN_NAME_TITLE, NotePad.Notes.COLUMN_NAME_NOTE }; // A label for the saved state of the activity private static final String ORIGINAL_CONTENT = "origContent"; // This Activity can be started by more than one action. Each action is represented // as a "state" constant private static final int STATE_EDIT = 0; private static final int STATE_INSERT = 1; // Global mutable variables private int mState; private Uri mUri; private Cursor mCursor; private EditText mText; private String mOriginalContent; /** * Defines a custom EditText View that draws lines between each line of text that is displayed. */ public static class LinedEditText extends EditText { private Rect mRect; private Paint mPaint; // This constructor is used by LayoutInflater public LinedEditText(Context context, AttributeSet attrs) { super(context, attrs); // Creates a Rect and a Paint object, and sets the style and color of the Paint object. mRect = new Rect(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x800000FF); } /** * This is called to draw the LinedEditText object * @param canvas The canvas on which the background is drawn. */ @Override protected void onDraw(Canvas canvas) { // Gets the number of lines of text in the View. int count = getLineCount(); // Gets the global Rect and Paint objects Rect r = mRect; Paint paint = mPaint; /* * Draws one line in the rectangle for every line of text in the EditText */ for (int i = 0; i < count; i++) { // Gets the baseline coordinates for the current line of text int baseline = getLineBounds(i, r); /* * Draws a line in the background from the left of the rectangle to the right, * at a vertical position one dip below the baseline, using the "paint" object * for details. */ canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); } // Finishes up by calling the parent method super.onDraw(canvas); } } /** * This method is called by Android when the Activity is first started. From the incoming * Intent, it determines what kind of editing is desired, and then does it. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Creates an Intent to use when the Activity object's result is sent back to the * caller. */ final Intent intent = getIntent(); /* * Sets up for the edit, based on the action specified for the incoming Intent. */ // Gets the action that triggered the intent filter for this Activity final String action = intent.getAction(); // For an edit action: if (Intent.ACTION_EDIT.equals(action)) { // Sets the Activity state to EDIT, and gets the URI for the data to be edited. mState = STATE_EDIT; mUri = intent.getData(); // For an insert or paste action: } else if (Intent.ACTION_INSERT.equals(action) || Intent.ACTION_PASTE.equals(action)) { // Sets the Activity state to INSERT, gets the general note URI, and inserts an // empty record in the provider mState = STATE_INSERT; mUri = getContentResolver().insert(intent.getData(), null); /* * If the attempt to insert the new note fails, shuts down this Activity. The * originating Activity receives back RESULT_CANCELED if it requested a result. * Logs that the insert failed. */ if (mUri == null) { // Writes the log identifier, a message, and the URI that failed. Log.e(TAG, "Failed to insert new note into " + getIntent().getData()); // Closes the activity. finish(); return; } // Since the new entry was created, this sets the result to be returned // set the result to be returned. setResult(RESULT_OK, (new Intent()).setAction(mUri.toString())); // If the action was other than EDIT or INSERT: } else { // Logs an error that the action was not understood, finishes the Activity, and // returns RESULT_CANCELED to an originating Activity. Log.e(TAG, "Unknown action, exiting"); finish(); return; } /* * Using the URI passed in with the triggering Intent, gets the note or notes in * the provider. * Note: This is being done on the UI thread. It will block the thread until the query * completes. In a sample app, going against a simple provider based on a local database, * the block will be momentary, but in a real app you should use * android.content.AsyncQueryHandler or android.os.AsyncTask. */ mCursor = managedQuery( mUri, // The URI that gets multiple notes from the provider. PROJECTION, // A projection that returns the note ID and note content for each note. null, // No "where" clause selection criteria. null, // No "where" clause selection values. null // Use the default sort order (modification date, descending) ); // For a paste, initializes the data from clipboard. // (Must be done after mCursor is initialized.) if (Intent.ACTION_PASTE.equals(action)) { // Does the paste performPaste(); // Switches the state to EDIT so the title can be modified. mState = STATE_EDIT; } // Sets the layout for this Activity. See res/layout/note_editor.xml setContentView(R.layout.note_editor); // Gets a handle to the EditText in the the layout. mText = (EditText) findViewById(R.id.note); /* * If this Activity had stopped previously, its state was written the ORIGINAL_CONTENT * location in the saved Instance state. This gets the state. */ if (savedInstanceState != null) { mOriginalContent = savedInstanceState.getString(ORIGINAL_CONTENT); } } /** * This method is called when the Activity is about to come to the foreground. This happens * when the Activity comes to the top of the task stack, OR when it is first starting. * * Moves to the first note in the list, sets an appropriate title for the action chosen by * the user, puts the note contents into the TextView, and saves the original text as a * backup. */ @Override protected void onResume() { super.onResume(); /* * mCursor is initialized, since onCreate() always precedes onResume for any running * process. This tests that it's not null, since it should always contain data. */ if (mCursor != null) { // Requery in case something changed while paused (such as the title) mCursor.requery(); /* Moves to the first record. Always call moveToFirst() before accessing data in * a Cursor for the first time. The semantics of using a Cursor are that when it is * created, its internal index is pointing to a "place" immediately before the first * record. */ mCursor.moveToFirst(); // Modifies the window title for the Activity according to the current Activity state. if (mState == STATE_EDIT) { // Set the title of the Activity to include the note title int colTitleIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE); String title = mCursor.getString(colTitleIndex); Resources res = getResources(); String text = String.format(res.getString(R.string.title_edit), title); setTitle(text); // Sets the title to "create" for inserts } else if (mState == STATE_INSERT) { setTitle(getText(R.string.title_create)); } /* * onResume() may have been called after the Activity lost focus (was paused). * The user was either editing or creating a note when the Activity paused. * The Activity should re-display the text that had been retrieved previously, but * it should not move the cursor. This helps the user to continue editing or entering. */ // Gets the note text from the Cursor and puts it in the TextView, but doesn't change // the text cursor's position. int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); String note = mCursor.getString(colNoteIndex); mText.setTextKeepState(note); // Stores the original note text, to allow the user to revert changes. if (mOriginalContent == null) { mOriginalContent = note; } /* * Something is wrong. The Cursor should always contain data. Report an error in the * note. */ } else { setTitle(getText(R.string.error_title)); mText.setText(getText(R.string.error_message)); } } /** * This method is called when an Activity loses focus during its normal operation, and is then * later on killed. The Activity has a chance to save its state so that the system can restore * it. * * Notice that this method isn't a normal part of the Activity lifecycle. It won't be called * if the user simply navigates away from the Activity. */ @Override protected void onSaveInstanceState(Bundle outState) { // Save away the original text, so we still have it if the activity // needs to be killed while paused. outState.putString(ORIGINAL_CONTENT, mOriginalContent); } /** * This method is called when the Activity loses focus. * * For Activity objects that edit information, onPause() may be the one place where changes are * saved. The Android application model is predicated on the idea that "save" and "exit" aren't * required actions. When users navigate away from an Activity, they shouldn't have to go back * to it to complete their work. The act of going away should save everything and leave the * Activity in a state where Android can destroy it if necessary. * * If the user hasn't done anything, then this deletes or clears out the note, otherwise it * writes the user's work to the provider. */ @Override protected void onPause() { super.onPause(); /* * Tests to see that the query operation didn't fail (see onCreate()). The Cursor object * will exist, even if no records were returned, unless the query failed because of some * exception or error. * */ if (mCursor != null) { // Get the current note text. String text = mText.getText().toString(); int length = text.length(); /* * If the Activity is in the midst of finishing and there is no text in the current * note, returns a result of CANCELED to the caller, and deletes the note. This is done * even if the note was being edited, the assumption being that the user wanted to * "clear out" (delete) the note. */ if (isFinishing() && (length == 0)) { setResult(RESULT_CANCELED); deleteNote(); /* * Writes the edits to the provider. The note has been edited if an existing note was * retrieved into the editor *or* if a new note was inserted. In the latter case, * onCreate() inserted a new empty note into the provider, and it is this new note * that is being edited. */ } else if (mState == STATE_EDIT) { // Creates a map to contain the new values for the columns updateNote(text, null); } else if (mState == STATE_INSERT) { updateNote(text, text); mState = STATE_EDIT; } } } /** * This method is called when the user clicks the device's Menu button the first time for * this Activity. Android passes in a Menu object that is populated with items. * * Builds the menus for editing and inserting, and adds in alternative actions that * registered themselves to handle the MIME types for this application. * * @param menu A Menu object to which items should be added. * @return True to display the menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.editor_options_menu, menu); // Only add extra menu items for a saved note if (mState == STATE_EDIT) { // Append to the // menu items for any other activities that can do stuff with it // as well. This does a query on the system for any activities that // implement the ALTERNATIVE_ACTION for our data, adding a menu item // for each one that is found. Intent intent = new Intent(null, mUri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NoteEditor.class), null, intent, 0, null); } return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // Check if note has changed and enable/disable the revert option int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); String savedNote = mCursor.getString(colNoteIndex); String currentNote = mText.getText().toString(); if (savedNote.equals(currentNote)) { menu.findItem(R.id.menu_revert).setVisible(false); } else { menu.findItem(R.id.menu_revert).setVisible(true); } return super.onPrepareOptionsMenu(menu); } /** * This method is called when a menu item is selected. Android passes in the selected item. * The switch statement in this method calls the appropriate method to perform the action the * user chose. * * @param item The selected MenuItem * @return True to indicate that the item was processed, and no further work is necessary. False * to proceed to further processing as indicated in the MenuItem object. */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle all of the possible menu actions. switch (item.getItemId()) { case R.id.menu_save: String text = mText.getText().toString(); updateNote(text, null); finish(); break; case R.id.menu_delete: deleteNote(); finish(); break; case R.id.menu_revert: cancelNote(); break; } return super.onOptionsItemSelected(item); } /** * A helper method that replaces the note's data with the contents of the clipboard. */ private final void performPaste() { // Gets a handle to the Clipboard Manager ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // Gets a content resolver instance ContentResolver cr = getContentResolver(); // Gets the clipboard data from the clipboard ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { String text=null; String title=null; // Gets the first item from the clipboard data ClipData.Item item = clip.getItemAt(0); // Tries to get the item's contents as a URI pointing to a note Uri uri = item.getUri(); // Tests to see that the item actually is an URI, and that the URI // is a content URI pointing to a provider whose MIME type is the same // as the MIME type supported by the Note pad provider. if (uri != null && NotePad.Notes.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) { // The clipboard holds a reference to data with a note MIME type. This copies it. Cursor orig = cr.query( uri, // URI for the content provider PROJECTION, // Get the columns referred to in the projection null, // No selection variables null, // No selection variables, so no criteria are needed null // Use the default sort order ); // If the Cursor is not null, and it contains at least one record // (moveToFirst() returns true), then this gets the note data from it. if (orig != null) { if (orig.moveToFirst()) { int colNoteIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_NOTE); int colTitleIndex = mCursor.getColumnIndex(NotePad.Notes.COLUMN_NAME_TITLE); text = orig.getString(colNoteIndex); title = orig.getString(colTitleIndex); } // Closes the cursor. orig.close(); } } // If the contents of the clipboard wasn't a reference to a note, then // this converts whatever it is to text. if (text == null) { text = item.coerceToText(this).toString(); } // Updates the current note with the retrieved title and text. updateNote(text, title); } } /** * Replaces the current note contents with the text and title provided as arguments. * @param text The new note contents to use. * @param title The new note title to use */ private final void updateNote(String text, String title) { // Sets up a map to contain values to be updated in the provider. ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, System.currentTimeMillis()); // If the action is to insert a new note, this creates an initial title for it. if (mState == STATE_INSERT) { // If no title was provided as an argument, create one from the note text. if (title == null) { // Get the note's length int length = text.length(); // Sets the title by getting a substring of the text that is 31 characters long // or the number of characters in the note plus one, whichever is smaller. title = text.substring(0, Math.min(30, length)); // If the resulting length is more than 30 characters, chops off any // trailing spaces if (length > 30) { int lastSpace = title.lastIndexOf(' '); if (lastSpace > 0) { title = title.substring(0, lastSpace); } } } // In the values map, sets the value of the title values.put(NotePad.Notes.COLUMN_NAME_TITLE, title); } else if (title != null) { // In the values map, sets the value of the title values.put(NotePad.Notes.COLUMN_NAME_TITLE, title); } // This puts the desired notes text into the map. values.put(NotePad.Notes.COLUMN_NAME_NOTE, text); /* * Updates the provider with the new values in the map. The ListView is updated * automatically. The provider sets this up by setting the notification URI for * query Cursor objects to the incoming URI. The content resolver is thus * automatically notified when the Cursor for the URI changes, and the UI is * updated. * Note: This is being done on the UI thread. It will block the thread until the * update completes. In a sample app, going against a simple provider based on a * local database, the block will be momentary, but in a real app you should use * android.content.AsyncQueryHandler or android.os.AsyncTask. */ getContentResolver().update( mUri, // The URI for the record to update. values, // The map of column names and new values to apply to them. null, // No selection criteria are used, so no where columns are necessary. null // No where columns are used, so no where arguments are necessary. ); } /** * This helper method cancels the work done on a note. It deletes the note if it was * newly created, or reverts to the original text of the note i */ private final void cancelNote() { if (mCursor != null) { if (mState == STATE_EDIT) { // Put the original note text back into the database mCursor.close(); mCursor = null; ContentValues values = new ContentValues(); values.put(NotePad.Notes.COLUMN_NAME_NOTE, mOriginalContent); getContentResolver().update(mUri, values, null, null); } else if (mState == STATE_INSERT) { // We inserted an empty note, make sure to delete it deleteNote(); } } setResult(RESULT_CANCELED); finish(); } /** * Take care of deleting a note. Simply deletes the entry. */ private final void deleteNote() { if (mCursor != null) { mCursor.close(); mCursor = null; getContentResolver().delete(mUri, null, null); mText.setText(""); } } } //src\com\example\android\notepad\NotePad.java /* package com.example.android.notepad; import android.net.Uri; import android.provider.BaseColumns; /** * Defines a contract between the Note Pad content provider and its clients. A contract defines the * information that a client needs to access the provider as one or more data tables. A contract * is a public, non-extendable (final) class that contains constants defining column names and * URIs. A well-written client depends only on the constants in the contract. */ public final class NotePad { public static final String AUTHORITY = "com.google.provider.NotePad"; // This class cannot be instantiated private NotePad() { } /** * Notes table contract */ public static final class Notes implements BaseColumns { // This class cannot be instantiated private Notes() {} /** * The table name offered by this provider */ public static final String TABLE_NAME = "notes"; /* * URI definitions */ /** * The scheme part for this provider's URI */ private static final String SCHEME = "content://"; /** * Path parts for the URIs */ /** * Path part for the Notes URI */ private static final String PATH_NOTES = "/notes"; /** * Path part for the Note ID URI */ private static final String PATH_NOTE_ID = "/notes/"; /** * 0-relative position of a note ID segment in the path part of a note ID URI */ public static final int NOTE_ID_PATH_POSITION = 1; /** * Path part for the Live Folder URI */ private static final String PATH_LIVE_FOLDER = "/live_folders/notes"; /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + PATH_NOTES); /** * The content URI base for a single note. Callers must * append a numeric note id to this Uri to retrieve a note */ public static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID); /** * The content URI match pattern for a single note, specified by its ID. Use this to match * incoming URIs or to construct an Intent. */ public static final Uri CONTENT_ID_URI_PATTERN = Uri.parse(SCHEME + AUTHORITY + PATH_NOTE_ID + "/#"); /** * The content Uri pattern for a notes listing for live folders */ public static final Uri LIVE_FOLDER_URI = Uri.parse(SCHEME + AUTHORITY + PATH_LIVE_FOLDER); /* * MIME type definitions */ /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single * note. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /* * Column definitions */ /** * Column name for the title of the note * <P>Type: TEXT</P> */ public static final String COLUMN_NAME_TITLE = "title"; /** * Column name of the note content * <P>Type: TEXT</P> */ public static final String COLUMN_NAME_NOTE = "note"; /** * Column name for the creation timestamp * <P>Type: INTEGER (long from System.curentTimeMillis())</P> */ public static final String COLUMN_NAME_CREATE_DATE = "created"; /** * Column name for the modification timestamp * <P>Type: INTEGER (long from System.curentTimeMillis())</P> */ public static final String COLUMN_NAME_MODIFICATION_DATE = "modified"; } } //src\com\example\android\notepad\NotePadProvider.java package com.example.android.notepad; import com.example.android.notepad.NotePad; import android.content.ClipDescription; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.content.ContentProvider.PipeDataWriter; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.LiveFolders; import android.text.TextUtils; import android.util.Log; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; /** * Provides access to a database of notes. Each note has a title, the note * itself, a creation date and a modified data. */ public class NotePadProvider extends ContentProvider implements PipeDataWriter<Cursor> { // Used for debugging and logging private static final String TAG = "NotePadProvider"; /** * The database that the provider uses as its underlying data store */ private static final String DATABASE_NAME = "note_pad.db"; /** * The database version */ private static final int DATABASE_VERSION = 2; /** * A projection map used to select columns from the database */ private static HashMap<String, String> sNotesProjectionMap; /** * A projection map used to select columns from the database */ private static HashMap<String, String> sLiveFolderProjectionMap; /** * Standard projection for the interesting columns of a normal note. */ private static final String[] READ_NOTE_PROJECTION = new String[] { NotePad.Notes._ID, // Projection position 0, the note's id NotePad.Notes.COLUMN_NAME_NOTE, // Projection position 1, the note's content NotePad.Notes.COLUMN_NAME_TITLE, // Projection position 2, the note's title }; private static final int READ_NOTE_NOTE_INDEX = 1; private static final int READ_NOTE_TITLE_INDEX = 2; /* * Constants used by the Uri matcher to choose an action based on the pattern * of the incoming URI */ // The incoming URI matches the Notes URI pattern private static final int NOTES = 1; // The incoming URI matches the Note ID URI pattern private static final int NOTE_ID = 2; // The incoming URI matches the Live Folder URI pattern private static final int LIVE_FOLDER_NOTES = 3; /** * A UriMatcher instance */ private static final UriMatcher sUriMatcher; // Handle to a new DatabaseHelper. private DatabaseHelper mOpenHelper; /** * A block that instantiates and sets static objects */ static { /* * Creates and initializes the URI matcher */ // Create a new instance sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // Add a pattern that routes URIs terminated with "notes" to a NOTES operation sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES); // Add a pattern that routes URIs terminated with "notes" plus an integer // to a note ID operation sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID); // Add a pattern that routes URIs terminated with live_folders/notes to a // live folder operation sUriMatcher.addURI(NotePad.AUTHORITY, "live_folders/notes", LIVE_FOLDER_NOTES); /* * Creates and initializes a projection map that returns all columns */ // Creates a new projection map instance. The map returns a column name // given a string. The two are usually equal. sNotesProjectionMap = new HashMap<String, String>(); // Maps the string "_ID" to the column name "_ID" sNotesProjectionMap.put(NotePad.Notes._ID, NotePad.Notes._ID); // Maps "title" to "title" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_TITLE, NotePad.Notes.COLUMN_NAME_TITLE); // Maps "note" to "note" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_NOTE); // Maps "created" to "created" sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, NotePad.Notes.COLUMN_NAME_CREATE_DATE); // Maps "modified" to "modified" sNotesProjectionMap.put( NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE); /* * Creates an initializes a projection map for handling Live Folders */ // Creates a new projection map instance sLiveFolderProjectionMap = new HashMap<String, String>(); // Maps "_ID" to "_ID AS _ID" for a live folder sLiveFolderProjectionMap.put(LiveFolders._ID, NotePad.Notes._ID + " AS " + LiveFolders._ID); // Maps "NAME" to "title AS NAME" sLiveFolderProjectionMap.put(LiveFolders.NAME, NotePad.Notes.COLUMN_NAME_TITLE + " AS " + LiveFolders.NAME); } /** * * This class helps open, create, and upgrade the database file. Set to package visibility * for testing purposes. */ static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { // calls the super constructor, requesting the default cursor factory. super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * * Creates the underlying database with table name and column names taken from the * NotePad class. */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + NotePad.Notes.TABLE_NAME + " (" + NotePad.Notes._ID + " INTEGER PRIMARY KEY," + NotePad.Notes.COLUMN_NAME_TITLE + " TEXT," + NotePad.Notes.COLUMN_NAME_NOTE + " TEXT," + NotePad.Notes.COLUMN_NAME_CREATE_DATE + " INTEGER," + NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE + " INTEGER" + ");"); } /** * * Demonstrates that the provider must consider what happens when the * underlying datastore is changed. In this sample, the database is upgraded the database * by destroying the existing data. * A real application should upgrade the database in place. */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Logs that the database is being upgraded Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // Kills the table and existing data db.execSQL("DROP TABLE IF EXISTS notes"); // Recreates the database with a new version onCreate(db); } } /** * * Initializes the provider by creating a new DatabaseHelper. onCreate() is called * automatically when Android creates the provider in response to a resolver request from a * client. */ @Override public boolean onCreate() { // Creates a new helper object. Note that the database itself isn't opened until // something tries to access it, and it's only created if it doesn't already exist. mOpenHelper = new DatabaseHelper(getContext()); // Assumes that any failures will be reported by a thrown exception. return true; } /** * This method is called when a client calls * {@link android.content.ContentResolver#query(Uri, String[], String, String[], String)}. * Queries the database and returns a cursor containing the results. * * @return A cursor containing the results of the query. The cursor exists but is empty if * the query returns no results or an exception occurs. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Constructs a new query builder and sets its table name SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(NotePad.Notes.TABLE_NAME); /** * Choose the projection and adjust the "where" clause based on URI pattern-matching. */ switch (sUriMatcher.match(uri)) { // If the incoming URI is for notes, chooses the Notes projection case NOTES: qb.setProjectionMap(sNotesProjectionMap); break; /* If the incoming URI is for a single note identified by its ID, chooses the * note ID projection, and appends "_ID = <noteID>" to the where clause, so that * it selects that single note */ case NOTE_ID: qb.setProjectionMap(sNotesProjectionMap); qb.appendWhere( NotePad.Notes._ID + // the name of the ID column "=" + // the position of the note ID itself in the incoming URI uri.getPathSegments().get(NotePad.Notes.NOTE_ID_PATH_POSITION)); break; case LIVE_FOLDER_NOTES: // If the incoming URI is from a live folder, chooses the live folder projection. qb.setProjectionMap(sLiveFolderProjectionMap); break; default: // If the URI doesn't match any of the known patterns, throw an exception. throw new IllegalArgumentException("Unknown URI " + uri); } String orderBy; // If no sort order is specified, uses the default if (TextUtils.isEmpty(sortOrder)) { orderBy = NotePad.Notes.DEFAULT_SORT_ORDER; } else { // otherwise, uses the incoming sort order orderBy = sortOrder; } // Opens the database object in "read" mode, since no writes need to be done. SQLiteDatabase db = mOpenHelper.getReadableDatabase(); /* * Performs the query. If no problems occur trying to read the database, then a Cursor * object is returned; otherwise, the cursor variable contains null. If no records were * selected, then the Cursor object is empty, and Cursor.getCount() returns 0. */ Cursor c = qb.query( db, // The database to query projection, // The columns to return from the query selection, // The columns for the where clause selectionArgs, // The values for the where clause null, // don't group the rows null, // don't filter by row groups orderBy // The sort order ); // Tells the Cursor what URI to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * This is called when a client calls {@link android.content.ContentResolver#getType(Uri)}. * Returns the MIME data type of the URI given as a parameter. * * @param uri The URI whose MIME type is desired. * @return The MIME type of the URI. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public String getType(Uri uri) { /** * Chooses the MIME type based on the incoming URI pattern */ switch (sUriMatcher.match(uri)) { // If the pattern is for notes or live folders, returns the general content type. case NOTES: case LIVE_FOLDER_NOTES: return NotePad.Notes.CONTENT_TYPE; // If the pattern is for note IDs, returns the note ID content type. case NOTE_ID: return NotePad.Notes.CONTENT_ITEM_TYPE; // If the URI pattern doesn't match any permitted patterns, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * This describes the MIME types that are supported for opening a note * URI as a stream. */ static ClipDescription NOTE_STREAM_TYPES = new ClipDescription(null, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }); /** * Returns the types of available data streams. URIs to specific notes are supported. * The application can convert such a note to a plain text stream. * * @param uri the URI to analyze * @param mimeTypeFilter The MIME type to check for. This method only returns a data stream * type for MIME types that match the filter. Currently, only text/plain MIME types match. * @return a data stream MIME type. Currently, only text/plan is returned. * @throws IllegalArgumentException if the URI pattern doesn't match any supported patterns. */ @Override public String[] getStreamTypes(Uri uri, String mimeTypeFilter) { /** * Chooses the data stream type based on the incoming URI pattern. */ switch (sUriMatcher.match(uri)) { // If the pattern is for notes or live folders, return null. Data streams are not // supported for this type of URI. case NOTES: case LIVE_FOLDER_NOTES: return null; // If the pattern is for note IDs and the MIME filter is text/plain, then return // text/plain case NOTE_ID: return NOTE_STREAM_TYPES.filterMimeTypes(mimeTypeFilter); // If the URI pattern doesn't match any permitted patterns, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * Returns a stream of data for each supported stream type. This method does a query on the * incoming URI, then uses * {@link android.content.ContentProvider#openPipeHelper(Uri, String, Bundle, Object, * PipeDataWriter)} to start another thread in which to convert the data into a stream. * * @param uri The URI pattern that points to the data stream * @param mimeTypeFilter A String containing a MIME type. This method tries to get a stream of * data with this MIME type. * @param opts Additional options supplied by the caller. Can be interpreted as * desired by the content provider. * @return AssetFileDescriptor A handle to the file. * @throws FileNotFoundException if there is no file associated with the incoming URI. */ @Override public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) throws FileNotFoundException { // Checks to see if the MIME type filter matches a supported MIME type. String[] mimeTypes = getStreamTypes(uri, mimeTypeFilter); // If the MIME type is supported if (mimeTypes != null) { // Retrieves the note for this URI. Uses the query method defined for this provider, // rather than using the database query method. Cursor c = query( uri, // The URI of a note READ_NOTE_PROJECTION, // Gets a projection containing the note's ID, title, // and contents null, // No WHERE clause, get all matching records null, // Since there is no WHERE clause, no selection criteria null // Use the default sort order (modification date, // descending ); // If the query fails or the cursor is empty, stop if (c == null || !c.moveToFirst()) { // If the cursor is empty, simply close the cursor and return if (c != null) { c.close(); } // If the cursor is null, throw an exception throw new FileNotFoundException("Unable to query " + uri); } // Start a new thread that pipes the stream data back to the caller. return new AssetFileDescriptor( openPipeHelper(uri, mimeTypes[0], opts, c, this), 0, AssetFileDescriptor.UNKNOWN_LENGTH); } // If the MIME type is not supported, return a read-only handle to the file. return super.openTypedAssetFile(uri, mimeTypeFilter, opts); } /** * Implementation of {@link android.content.ContentProvider.PipeDataWriter} * to perform the actual work of converting the data in one of cursors to a * stream of data for the client to read. */ @Override public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, Bundle opts, Cursor c) { // We currently only support conversion-to-text from a single note entry, // so no need for cursor data type checking here. FileOutputStream fout = new FileOutputStream(output.getFileDescriptor()); PrintWriter pw = null; try { pw = new PrintWriter(new OutputStreamWriter(fout, "UTF-8")); pw.println(c.getString(READ_NOTE_TITLE_INDEX)); pw.println(""); pw.println(c.getString(READ_NOTE_NOTE_INDEX)); } catch (UnsupportedEncodingException e) { Log.w(TAG, "Ooops", e); } finally { c.close(); if (pw != null) { pw.flush(); } try { fout.close(); } catch (IOException e) { } } } /** * This is called when a client calls * {@link android.content.ContentResolver#insert(Uri, ContentValues)}. * Inserts a new row into the database. This method sets up default values for any * columns that are not included in the incoming map. * If rows were inserted, then listeners are notified of the change. * @return The row ID of the inserted row. * @throws SQLException if the insertion fails. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { // Validates the incoming URI. Only the full provider URI is allowed for inserts. if (sUriMatcher.match(uri) != NOTES) { throw new IllegalArgumentException("Unknown URI " + uri); } // A map to hold the new record's values. ContentValues values; // If the incoming values map is not null, uses it for the new values. if (initialValues != null) { values = new ContentValues(initialValues); } else { // Otherwise, create a new value map values = new ContentValues(); } // Gets the current system time in milliseconds Long now = Long.valueOf(System.currentTimeMillis()); // If the values map doesn't contain the creation date, sets the value to the current time. if (values.containsKey(NotePad.Notes.COLUMN_NAME_CREATE_DATE) == false) { values.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, now); } // If the values map doesn't contain the modification date, sets the value to the current // time. if (values.containsKey(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE) == false) { values.put(NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE, now); } // If the values map doesn't contain a title, sets the value to the default title. if (values.containsKey(NotePad.Notes.COLUMN_NAME_TITLE) == false) { Resources r = Resources.getSystem(); values.put(NotePad.Notes.COLUMN_NAME_TITLE, r.getString(android.R.string.untitled)); } // If the values map doesn't contain note text, sets the value to an empty string. if (values.containsKey(NotePad.Notes.COLUMN_NAME_NOTE) == false) { values.put(NotePad.Notes.COLUMN_NAME_NOTE, ""); } // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); // Performs the insert and returns the ID of the new note. long rowId = db.insert( NotePad.Notes.TABLE_NAME, // The table to insert into. NotePad.Notes.COLUMN_NAME_NOTE, // A hack, SQLite sets this column value to null // if values is empty. values // A map of column names, and the values to insert // into the columns. ); // If the insert succeeded, the row ID exists. if (rowId > 0) { // Creates a URI with the note ID pattern and the new row ID appended to it. Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, rowId); // Notifies observers registered against this provider that the data changed. getContext().getContentResolver().notifyChange(noteUri, null); return noteUri; } // If the insert didn't succeed, then the rowID is <= 0. Throws an exception. throw new SQLException("Failed to insert row into " + uri); } /** * This is called when a client calls * {@link android.content.ContentResolver#delete(Uri, String, String[])}. * Deletes records from the database. If the incoming URI matches the note ID URI pattern, * this method deletes the one record specified by the ID in the URI. Otherwise, it deletes a * a set of records. The record or records must also match the input selection criteria * specified by where and whereArgs. * * If rows were deleted, then listeners are notified of the change. * @return If a "where" clause is used, the number of rows affected is returned, otherwise * 0 is returned. To delete all rows and get a row count, use "1" as the where clause. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); String finalWhere; int count; // Does the delete based on the incoming URI pattern. switch (sUriMatcher.match(uri)) { // If the incoming pattern matches the general pattern for notes, does a delete // based on the incoming "where" columns and arguments. case NOTES: count = db.delete( NotePad.Notes.TABLE_NAME, // The database table name where, // The incoming where clause column names whereArgs // The incoming where clause values ); break; // If the incoming URI matches a single note ID, does the delete based on the // incoming data, but modifies the where clause to restrict it to the // particular note ID. case NOTE_ID: /* * Starts a final WHERE clause by restricting it to the * desired note ID. */ finalWhere = NotePad.Notes._ID + // The ID column name " = " + // test for equality uri.getPathSegments(). // the incoming note ID get(NotePad.Notes.NOTE_ID_PATH_POSITION) ; // If there were additional selection criteria, append them to the final // WHERE clause if (where != null) { finalWhere = finalWhere + " AND " + where; } // Performs the delete. count = db.delete( NotePad.Notes.TABLE_NAME, // The database table name. finalWhere, // The final WHERE clause whereArgs // The incoming where clause values. ); break; // If the incoming pattern is invalid, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } /*Gets a handle to the content resolver object for the current context, and notifies it * that the incoming URI changed. The object passes this along to the resolver framework, * and observers that have registered themselves for the provider are notified. */ getContext().getContentResolver().notifyChange(uri, null); // Returns the number of rows deleted. return count; } /** * This is called when a client calls * {@link android.content.ContentResolver#update(Uri,ContentValues,String,String[])} * Updates records in the database. The column names specified by the keys in the values map * are updated with new data specified by the values in the map. If the incoming URI matches the * note ID URI pattern, then the method updates the one record specified by the ID in the URI; * otherwise, it updates a set of records. The record or records must match the input * selection criteria specified by where and whereArgs. * If rows were updated, then listeners are notified of the change. * * @param uri The URI pattern to match and update. * @param values A map of column names (keys) and new values (values). * @param where An SQL "WHERE" clause that selects records based on their column values. If this * is null, then all records that match the URI pattern are selected. * @param whereArgs An array of selection criteria. If the "where" param contains value * placeholders ("?"), then each placeholder is replaced by the corresponding element in the * array. * @return The number of rows updated. * @throws IllegalArgumentException if the incoming URI pattern is invalid. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { // Opens the database object in "write" mode. SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count; String finalWhere; // Does the update based on the incoming URI pattern switch (sUriMatcher.match(uri)) { // If the incoming URI matches the general notes pattern, does the update based on // the incoming data. case NOTES: // Does the update and returns the number of rows updated. count = db.update( NotePad.Notes.TABLE_NAME, // The database table name. values, // A map of column names and new values to use. where, // The where clause column names. whereArgs // The where clause column values to select on. ); break; // If the incoming URI matches a single note ID, does the update based on the incoming // data, but modifies the where clause to restrict it to the particular note ID. case NOTE_ID: // From the incoming URI, get the note ID String noteId = uri.getPathSegments().get(NotePad.Notes.NOTE_ID_PATH_POSITION); /* * Starts creating the final WHERE clause by restricting it to the incoming * note ID. */ finalWhere = NotePad.Notes._ID + // The ID column name " = " + // test for equality uri.getPathSegments(). // the incoming note ID get(NotePad.Notes.NOTE_ID_PATH_POSITION) ; // If there were additional selection criteria, append them to the final WHERE // clause if (where !=null) { finalWhere = finalWhere + " AND " + where; } // Does the update and returns the number of rows updated. count = db.update( NotePad.Notes.TABLE_NAME, // The database table name. values, // A map of column names and new values to use. finalWhere, // The final WHERE clause to use // placeholders for whereArgs whereArgs // The where clause column values to select on, or // null if the values are in the where argument. ); break; // If the incoming pattern is invalid, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } /*Gets a handle to the content resolver object for the current context, and notifies it * that the incoming URI changed. The object passes this along to the resolver framework, * and observers that have registered themselves for the provider are notified. */ getContext().getContentResolver().notifyChange(uri, null); // Returns the number of rows updated. return count; } /** * A test package can call this to get a handle to the database underlying NotePadProvider, * so it can insert test data into the database. The test case class is responsible for * instantiating the provider in a test context; {@link android.test.ProviderTestCase2} does * this during the call to setUp() * * @return a handle to the database helper object for the provider's data. */ DatabaseHelper getOpenHelperForTest() { return mOpenHelper; } } //src\com\example\android\notepad\NotesList.java package com.example.android.notepad; import com.example.android.notepad.NotePad; import android.app.ListActivity; import android.content.ClipboardManager; import android.content.ClipData; import android.content.ComponentName; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; /** * Displays a list of notes. Will display notes from the {@link Uri} * provided in the incoming Intent if there is one, otherwise it defaults to displaying the * contents of the {@link NotePadProvider}. * * NOTE: Notice that the provider operations in this Activity are taking place on the UI thread. * This is not a good practice. It is only done here to make the code more readable. A real * application should use the {@link android.content.AsyncQueryHandler} or * {@link android.os.AsyncTask} object to perform operations asynchronously on a separate thread. */ public class NotesList extends ListActivity { // For logging and debugging private static final String TAG = "NotesList"; /** * The columns needed by the cursor adapter */ private static final String[] PROJECTION = new String[] { NotePad.Notes._ID, // 0 NotePad.Notes.COLUMN_NAME_TITLE, // 1 }; /** The index of the title column */ private static final int COLUMN_INDEX_TITLE = 1; /** * onCreate is called when Android starts this Activity from scratch. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The user does not need to hold down the key to use menu shortcuts. setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); /* If no data is given in the Intent that started this Activity, then this Activity * was started when the intent filter matched a MAIN action. We should use the default * provider URI. */ // Gets the intent that started this Activity. Intent intent = getIntent(); // If there is no data associated with the Intent, sets the data to the default URI, which // accesses a list of notes. if (intent.getData() == null) { intent.setData(NotePad.Notes.CONTENT_URI); } /* * Sets the callback for context menu activation for the ListView. The listener is set * to be this Activity. The effect is that context menus are enabled for items in the * ListView, and the context menu is handled by a method in NotesList. */ getListView().setOnCreateContextMenuListener(this); /* Performs a managed query. The Activity handles closing and requerying the cursor * when needed. * * Please see the introductory note about performing provider operations on the UI thread. */ Cursor cursor = managedQuery( getIntent().getData(), // Use the default content URI for the provider. PROJECTION, // Return the note ID and title for each note. null, // No where clause, return all records. null, // No where clause, therefore no where column values. NotePad.Notes.DEFAULT_SORT_ORDER // Use the default sort order. ); /* * The following two arrays create a "map" between columns in the cursor and view IDs * for items in the ListView. Each element in the dataColumns array represents * a column name; each element in the viewID array represents the ID of a View. * The SimpleCursorAdapter maps them in ascending order to determine where each column * value will appear in the ListView. */ // The names of the cursor columns to display in the view, initialized to the title column String[] dataColumns = { NotePad.Notes.COLUMN_NAME_TITLE } ; // The view IDs that will display the cursor columns, initialized to the TextView in // noteslist_item.xml int[] viewIDs = { android.R.id.text1 }; // Creates the backing adapter for the ListView. SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, // The Context for the ListView R.layout.noteslist_item, // Points to the XML for a list item cursor, // The cursor to get items from dataColumns, viewIDs ); // Sets the ListView's adapter to be the cursor adapter that was just created. setListAdapter(adapter); } /** * Called when the user clicks the device's Menu button the first time for * this Activity. Android passes in a Menu object that is populated with items. * * Sets up a menu that provides the Insert option plus a list of alternative actions for * this Activity. Other applications that want to handle notes can "register" themselves in * Android by providing an intent filter that includes the category ALTERNATIVE and the * mimeTYpe NotePad.Notes.CONTENT_TYPE. If they do this, the code in onCreateOptionsMenu() * will add the Activity that contains the intent filter to its list of options. In effect, * the menu will offer the user other applications that can handle notes. * @param menu A Menu object, to which menu items should be added. * @return True, always. The menu should be displayed. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_options_menu, menu); // Generate any additional actions that can be performed on the // overall list. In a normal install, there are no additional // actions found here, but this allows other applications to extend // our menu with their own actions. Intent intent = new Intent(null, getIntent().getData()); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NotesList.class), null, intent, 0, null); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // The paste menu item is enabled if there is data on the clipboard. ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); MenuItem mPasteItem = menu.findItem(R.id.menu_paste); // If the clipboard contains an item, enables the Paste option on the menu. if (clipboard.hasPrimaryClip()) { mPasteItem.setEnabled(true); } else { // If the clipboard is empty, disables the menu's Paste option. mPasteItem.setEnabled(false); } // Gets the number of notes currently being displayed. final boolean haveItems = getListAdapter().getCount() > 0; // If there are any notes in the list (which implies that one of // them is selected), then we need to generate the actions that // can be performed on the current selection. This will be a combination // of our own specific actions along with any extensions that can be // found. if (haveItems) { // This is the selected item. Uri uri = ContentUris.withAppendedId(getIntent().getData(), getSelectedItemId()); // Creates an array of Intents with one element. This will be used to send an Intent // based on the selected menu item. Intent[] specifics = new Intent[1]; // Sets the Intent in the array to be an EDIT action on the URI of the selected note. specifics[0] = new Intent(Intent.ACTION_EDIT, uri); // Creates an array of menu items with one element. This will contain the EDIT option. MenuItem[] items = new MenuItem[1]; // Creates an Intent with no specific action, using the URI of the selected note. Intent intent = new Intent(null, uri); /* Adds the category ALTERNATIVE to the Intent, with the note ID URI as its * data. This prepares the Intent as a place to group alternative options in the * menu. */ intent.addCategory(Intent.CATEGORY_ALTERNATIVE); /* * Add alternatives to the menu */ menu.addIntentOptions( Menu.CATEGORY_ALTERNATIVE, // Add the Intents as options in the alternatives group. Menu.NONE, // A unique item ID is not required. Menu.NONE, // The alternatives don't need to be in order. null, // The caller's name is not excluded from the group. specifics, // These specific options must appear first. intent, // These Intent objects map to the options in specifics. Menu.NONE, // No flags are required. items // The menu items generated from the specifics-to- // Intents mapping ); // If the Edit menu item exists, adds shortcuts for it. if (items[0] != null) { // Sets the Edit menu item shortcut to numeric "1", letter "e" items[0].setShortcut('1', 'e'); } } else { // If the list is empty, removes any existing alternative actions from the menu menu.removeGroup(Menu.CATEGORY_ALTERNATIVE); } // Displays the menu return true; } /** * This method is called when the user selects an option from the menu, but no item * in the list is selected. If the option was INSERT, then a new Intent is sent out with action * ACTION_INSERT. The data from the incoming Intent is put into the new Intent. In effect, * this triggers the NoteEditor activity in the NotePad application. * * If the item was not INSERT, then most likely it was an alternative option from another * application. The parent method is called to process the item. * @param item The menu item that was selected by the user * @return True, if the INSERT menu item was selected; otherwise, the result of calling * the parent method. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add: /* * Launches a new Activity using an Intent. The intent filter for the Activity * has to have action ACTION_INSERT. No category is set, so DEFAULT is assumed. * In effect, this starts the NoteEditor Activity in NotePad. */ startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData())); return true; case R.id.menu_paste: /* * Launches a new Activity using an Intent. The intent filter for the Activity * has to have action ACTION_PASTE. No category is set, so DEFAULT is assumed. * In effect, this starts the NoteEditor Activity in NotePad. */ startActivity(new Intent(Intent.ACTION_PASTE, getIntent().getData())); return true; default: return super.onOptionsItemSelected(item); } } /** * This method is called when the user context-clicks a note in the list. NotesList registers * itself as the handler for context menus in its ListView (this is done in onCreate()). * * The only available options are COPY and DELETE. * * Context-click is equivalent to long-press. * * @param menu A ContexMenu object to which items should be added. * @param view The View for which the context menu is being constructed. * @param menuInfo Data associated with view. * @throws ClassCastException */ @Override public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { // The data from the menu item. AdapterView.AdapterContextMenuInfo info; // Tries to get the position of the item in the ListView that was long-pressed. try { // Casts the incoming data object into the type for AdapterView objects. info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { // If the menu object can't be cast, logs an error. Log.e(TAG, "bad menuInfo", e); return; } /* * Gets the data associated with the item at the selected position. getItem() returns * whatever the backing adapter of the ListView has associated with the item. In NotesList, * the adapter associated all of the data for a note with its list item. As a result, * getItem() returns that data as a Cursor. */ Cursor cursor = (Cursor) getListAdapter().getItem(info.position); // If the cursor is empty, then for some reason the adapter can't get the data from the // provider, so returns null to the caller. if (cursor == null) { // For some reason the requested item isn't available, do nothing return; } // Inflate menu from XML resource MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.list_context_menu, menu); // Sets the menu header to be the title of the selected note. menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_TITLE)); // Append to the // menu items for any other activities that can do stuff with it // as well. This does a query on the system for any activities that // implement the ALTERNATIVE_ACTION for our data, adding a menu item // for each one that is found. Intent intent = new Intent(null, Uri.withAppendedPath(getIntent().getData(), Integer.toString((int) info.id) )); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, new ComponentName(this, NotesList.class), null, intent, 0, null); } /** * This method is called when the user selects an item from the context menu * (see onCreateContextMenu()). The only menu items that are actually handled are DELETE and * COPY. Anything else is an alternative option, for which default handling should be done. * * @param item The selected menu item * @return True if the menu item was DELETE, and no default processing is need, otherwise false, * which triggers the default handling of the item. * @throws ClassCastException */ @Override public boolean onContextItemSelected(MenuItem item) { // The data from the menu item. AdapterView.AdapterContextMenuInfo info; /* * Gets the extra info from the menu item. When an note in the Notes list is long-pressed, a * context menu appears. The menu items for the menu automatically get the data * associated with the note that was long-pressed. The data comes from the provider that * backs the list. * * The note's data is passed to the context menu creation routine in a ContextMenuInfo * object. * * When one of the context menu items is clicked, the same data is passed, along with the * note ID, to onContextItemSelected() via the item parameter. */ try { // Casts the data object in the item into the type for AdapterView objects. info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { // If the object can't be cast, logs an error Log.e(TAG, "bad menuInfo", e); // Triggers default processing of the menu item. return false; } // Appends the selected note's ID to the URI sent with the incoming Intent. Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id); /* * Gets the menu item's ID and compares it to known actions. */ switch (item.getItemId()) { case R.id.context_open: // Launch activity to view/edit the currently selected item startActivity(new Intent(Intent.ACTION_EDIT, noteUri)); return true; case R.id.context_copy: // Gets a handle to the clipboard service. ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // Copies the notes URI to the clipboard. In effect, this copies the note itself clipboard.setPrimaryClip(ClipData.newUri( // new clipboard item holding a URI getContentResolver(), // resolver to retrieve URI info "Note", // label for the clip noteUri) // the URI ); // Returns to the caller and skips further processing. return true; case R.id.context_delete: // Deletes the note from the provider by passing in a URI in note ID format. // Please see the introductory note about performing provider operations on the // UI thread. getContentResolver().delete( noteUri, // The URI of the provider null, // No where clause is needed, since only a single note ID is being // passed in. null // No where clause is used, so no where arguments are needed. ); // Returns to the caller and skips further processing. return true; default: return super.onContextItemSelected(item); } } /** * This method is called when the user clicks a note in the displayed list. * * This method handles incoming actions of either PICK (get data from the provider) or * GET_CONTENT (get or create data). If the incoming action is EDIT, this method sends a * new Intent to start NoteEditor. * @param l The ListView that contains the clicked item * @param v The View of the individual item * @param position The position of v in the displayed list * @param id The row ID of the clicked item */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { // Constructs a new URI from the incoming URI and the row ID Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); // Gets the action from the incoming Intent String action = getIntent().getAction(); // Handles requests for note data if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { // Sets the result to return to the component that called this Activity. The // result contains the new URI setResult(RESULT_OK, new Intent().setData(uri)); } else { // Sends out an Intent to start an Activity that can handle ACTION_EDIT. The // Intent's data is the note ID URI. The effect is to call NoteEdit. startActivity(new Intent(Intent.ACTION_EDIT, uri)); } } } //src\com\example\android\notepad\NotesLiveFolder.java package com.example.android.notepad; import com.example.android.notepad.NotePad; import android.app.Activity; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.os.Bundle; import android.provider.LiveFolders; /** * This Activity creates a live folder Intent and * sends it back to HOME. From the data in the Intent, HOME creates a live folder and displays * its icon in the Home view. * When the user clicks the icon, Home uses the data it got from the Intent to retrieve information * from a content provider and display it in a View. * * The intent filter for this Activity is set to ACTION_CREATE_LIVE_FOLDER, which * HOME sends in response to a long press and selection of Live Folder. */ public class NotesLiveFolder extends Activity { /** * All of the work is done in onCreate(). The Activity doesn't actually display a UI. * Instead, it sets up an Intent and returns it to its caller (the HOME activity). */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Gets the incoming Intent and its action. If the incoming Intent was * ACTION_CREATE_LIVE_FOLDER, then create an outgoing Intent with the * necessary data and send back OK. Otherwise, send back CANCEL. */ final Intent intent = getIntent(); final String action = intent.getAction(); if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) { // Creates a new Intent. final Intent liveFolderIntent = new Intent(); /* * The following statements put data into the outgoing Intent. Please see * {@link android.provider.LiveFolders for a detailed description of these * data values. From this data, HOME sets up a live folder. */ // Sets the URI pattern for the content provider backing the folder. liveFolderIntent.setData(NotePad.Notes.LIVE_FOLDER_URI); // Adds the display name of the live folder as an Extra string. String foldername = getString(R.string.live_folder_name); liveFolderIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, foldername); // Adds the display icon of the live folder as an Extra resource. ShortcutIconResource foldericon = Intent.ShortcutIconResource.fromContext(this, R.drawable.live_folder_notes); liveFolderIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON, foldericon); // Add the display mode of the live folder as an integer. The specified // mode causes the live folder to display as a list. liveFolderIntent.putExtra( LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST); /* * Adds a base action for items in the live folder list, as an Intent. When the * user clicks an individual note in the list, the live folder fires this Intent. * * Its action is ACTION_EDIT, so it triggers the Note Editor activity. Its * data is the URI pattern for a single note identified by its ID. The live folder * automatically adds the ID value of the selected item to the URI pattern. * * As a result, Note Editor is triggered and gets a single note to retrieve by ID. */ Intent returnIntent = new Intent(Intent.ACTION_EDIT, NotePad.Notes.CONTENT_ID_URI_PATTERN); liveFolderIntent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT, returnIntent); /* Creates an ActivityResult object to propagate back to HOME. Set its result indicator * to OK, and sets the returned Intent to the live folder Intent that was just * constructed. */ setResult(RESULT_OK, liveFolderIntent); } else { // If the original action was not ACTION_CREATE_LIVE_FOLDER, creates an // ActivityResult with the indicator set to CANCELED, but do not return an Intent setResult(RESULT_CANCELED); } // Closes the Activity. The ActivityObject is propagated back to the caller. finish(); } } //src\com\example\android\notepad\TitleEditor.java package com.example.android.notepad; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.EditText; /** * This Activity allows the user to edit a note's title. It displays a floating window * containing an EditText. * * NOTE: Notice that the provider operations in this Activity are taking place on the UI thread. * This is not a good practice. It is only done here to make the code more readable. A real * application should use the {@link android.content.AsyncQueryHandler} * or {@link android.os.AsyncTask} object to perform operations asynchronously on a separate thread. */ public class TitleEditor extends Activity { /** * This is a special intent action that means "edit the title of a note". */ public static final String EDIT_TITLE_ACTION = "com.android.notepad.action.EDIT_TITLE"; // Creates a projection that returns the note ID and the note contents. private static final String[] PROJECTION = new String[] { NotePad.Notes._ID, // 0 NotePad.Notes.COLUMN_NAME_TITLE, // 1 }; // The position of the title column in a Cursor returned by the provider. private static final int COLUMN_INDEX_TITLE = 1; // A Cursor object that will contain the results of querying the provider for a note. private Cursor mCursor; // An EditText object for preserving the edited title. private EditText mText; // A URI object for the note whose title is being edited. private Uri mUri; /** * This method is called by Android when the Activity is first started. From the incoming * Intent, it determines what kind of editing is desired, and then does it. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the View for this Activity object's UI. setContentView(R.layout.title_editor); // Get the Intent that activated this Activity, and from it get the URI of the note whose // title we need to edit. mUri = getIntent().getData(); /* * Using the URI passed in with the triggering Intent, gets the note. * * Note: This is being done on the UI thread. It will block the thread until the query * completes. In a sample app, going against a simple provider based on a local database, * the block will be momentary, but in a real app you should use * android.content.AsyncQueryHandler or android.os.AsyncTask. */ mCursor = managedQuery( mUri, // The URI for the note that is to be retrieved. PROJECTION, // The columns to retrieve null, // No selection criteria are used, so no where columns are needed. null, // No where columns are used, so no where values are needed. null // No sort order is needed. ); // Gets the View ID for the EditText box mText = (EditText) this.findViewById(R.id.title); } /** * This method is called when the Activity is about to come to the foreground. This happens * when the Activity comes to the top of the task stack, OR when it is first starting. * * Displays the current title for the selected note. */ @Override protected void onResume() { super.onResume(); // Verifies that the query made in onCreate() actually worked. If it worked, then the // Cursor object is not null. If it is *empty*, then mCursor.getCount() == 0. if (mCursor != null) { // The Cursor was just retrieved, so its index is set to one record *before* the first // record retrieved. This moves it to the first record. mCursor.moveToFirst(); // Displays the current title text in the EditText object. mText.setText(mCursor.getString(COLUMN_INDEX_TITLE)); } } /** * This method is called when the Activity loses focus. * * For Activity objects that edit information, onPause() may be the one place where changes are * saved. The Android application model is predicated on the idea that "save" and "exit" aren't * required actions. When users navigate away from an Activity, they shouldn't have to go back * to it to complete their work. The act of going away should save everything and leave the * Activity in a state where Android can destroy it if necessary. * * Updates the note with the text currently in the text box. */ @Override protected void onPause() { super.onPause(); // Verifies that the query made in onCreate() actually worked. If it worked, then the // Cursor object is not null. If it is *empty*, then mCursor.getCount() == 0. if (mCursor != null) { // Creates a values map for updating the provider. ContentValues values = new ContentValues(); // In the values map, sets the title to the current contents of the edit box. values.put(NotePad.Notes.COLUMN_NAME_TITLE, mText.getText().toString()); /* * Updates the provider with the note's new title. * * Note: This is being done on the UI thread. It will block the thread until the * update completes. In a sample app, going against a simple provider based on a * local database, the block will be momentary, but in a real app you should use * android.content.AsyncQueryHandler or android.os.AsyncTask. */ getContentResolver().update( mUri, // The URI for the note to update. values, // The values map containing the columns to update and the values to use. null, // No selection criteria is used, so no "where" columns are needed. null // No "where" columns are used, so no "where" values are needed. ); } } public void onClickOk(View v) { finish(); } } // //res\layout\note_editor.xml <?xml version="1.0" encoding="utf-8"?> <view xmlns:android="http://schemas.android.com/apk/res/android" class="com.example.android.notepad.NoteEditor$LinedEditText" android:id="@+id/note" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent" android:padding="5dp" android:scrollbars="vertical" android:fadingEdge="vertical" android:gravity="top" android:textSize="22sp" android:capitalize="sentences" /> //res\layout\noteslist_item.xml <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_vertical" android:paddingLeft="5dip" android:singleLine="true" /> //res\layout\title_editor.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:paddingLeft="6dip" android:paddingRight="6dip" android:paddingBottom="3dip"> <EditText android:id="@+id/title" android:maxLines="1" android:layout_marginTop="2dp" android:layout_marginBottom="15dp" android:layout_width="wrap_content" android:ems="25" android:layout_height="wrap_content" android:autoText="true" android:capitalize="sentences" android:scrollHorizontally="true" /> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/button_ok" android:onClick="onClickOk" /> </LinearLayout> // //res\menu\editor_options_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_save" android:icon="@drawable/ic_menu_save" android:alphabeticShortcut='s' android:title="@string/menu_save" android:showAsAction="ifRoom|withText" /> <item android:id="@+id/menu_revert" android:icon="@drawable/ic_menu_revert" android:title="@string/menu_revert" /> <item android:id="@+id/menu_delete" android:icon="@drawable/ic_menu_delete" android:title="@string/menu_delete" android:showAsAction="ifRoom|withText" /> </menu> //res\menu\list_context_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/context_open" android:title="@string/menu_open" /> <item android:id="@+id/context_copy" android:title="@string/menu_copy" /> <item android:id="@+id/context_delete" android:title="@string/menu_delete" /> </menu> //res\menu\list_options_menu.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <!-- This is our one standard application action (creating a new note). --> <item android:id="@+id/menu_add" android:icon="@drawable/ic_menu_compose" android:title="@string/menu_add" android:alphabeticShortcut='a' android:showAsAction="always" /> <!-- If there is currently data in the clipboard, this adds a PASTE menu item to the menu so that the user can paste in the data.. --> <item android:id="@+id/menu_paste" android:icon="@drawable/ic_menu_compose" android:title="@string/menu_paste" android:alphabeticShortcut='p' /> </menu> // //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">NotePad</string> <string name="live_folder_name">Notes</string> <string name="title_edit_title">Note title:</string> <string name="title_create">New note</string> <string name="title_edit">Edit: %1$s</string> <string name="title_notes_list">Notes</string> <string name="menu_add">New note</string> <string name="menu_save">Save</string> <string name="menu_delete">Delete</string> <string name="menu_open">Open</string> <string name="menu_revert">Revert changes</string> <string name="menu_copy">Copy</string> <string name="menu_paste">Paste</string> <string name="button_ok">OK</string> <string name="text_title">Title:</string> <string name="resolve_edit">Edit note</string> <string name="resolve_title">Edit title</string> <string name="error_title">Error</string> <string name="error_message">Error loading note</string> <string name="nothing_to_save">There is nothing to save</string> </resources>
Get value from EditText
package app.test; import android.app.Activity; 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 savedInstanceState) { super.onCreate(savedInstanceState); setTitle("EditTextActivity"); setContentView(R.layout.main); find_and_modify_text_view(); } private void find_and_modify_text_view() { Button get_edit_view_button = (Button) findViewById(R.id.get_edit_view_button); get_edit_view_button.setOnClickListener(get_edit_view_button_listener); } private Button.OnClickListener get_edit_view_button_listener = new Button.OnClickListener() { public void onClick(View v) { EditText edit_text = (EditText) findViewById(R.id.edit_text); CharSequence edit_text_value = edit_text.getText(); setTitle("EditText:" + edit_text_value); } }; } //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"> <EditText android:id="@+id/edit_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Input text here" /> <Button android:id="@+id/get_edit_view_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get value from EditView" /> </LinearLayout>
Change color and size for EditText
package app.test; import android.app.Activity; import android.graphics.Color; 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 EditText edittext = (EditText) findViewById(R.id.testEditText); final Button changeButton = (Button) findViewById(R.id.layoutButton); changeButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption(edittext); } }); final Button changeButton2 = (Button) findViewById(R.id.textColorButton); changeButton2.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { changeOption2(edittext); } }); } public void changeOption(EditText edittext) { if (edittext.getHeight() == 100) { edittext.setHeight(30); } else { edittext.setHeight(100); } } public void changeOption2(EditText edittext) { edittext.setTextColor(Color.RED); } } //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" > <EditText android:id="@+id/testEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/layoutButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Layout"/> <Button android:id="@+id/textColorButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change Text Color"/> </LinearLayout>
EditText focus event listener
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn1 = (Button) findViewById(R.id.btn1); btn1.setOnClickListener(btnListener); Button btn2 = (Button) findViewById(R.id.btn2); btn2.setOnClickListener(btnListener); EditText txt1 = (EditText) findViewById(R.id.txt1); txt1.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { Toast.makeText(getBaseContext(), ((EditText) v).getId() + " has focus - " + hasFocus, Toast.LENGTH_LONG).show(); } }); } private OnClickListener btnListener = new OnClickListener() { public void onClick(View v) { Toast.makeText(getBaseContext(), ((Button) v).getText() + " was clicked", Toast.LENGTH_LONG) .show(); } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: Toast.makeText(getBaseContext(), "Center was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_LEFT: Toast.makeText(getBaseContext(), "Left arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_RIGHT: Toast.makeText(getBaseContext(), "Right arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_UP: Toast.makeText(getBaseContext(), "Up arrow was clicked", Toast.LENGTH_LONG).show(); break; case KeyEvent.KEYCODE_DPAD_DOWN: Toast.makeText(getBaseContext(), "Down arrow was clicked", Toast.LENGTH_LONG).show(); break; } return false; } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:layout_width="214dp" android:layout_height="wrap_content" android:text="Your Name" /> <EditText android:id="@+id/txt1" android:layout_width="214dp" android:layout_height="wrap_content" /> <Button android:id="@+id/btn1" android:layout_width="106dp" android:layout_height="wrap_content" android:text="OK" /> <Button android:id="@+id/btn2" android:layout_width="106dp" android:layout_height="wrap_content" android:text="Cancel" /> </LinearLayout>
Adding EditText to Activity
<?xml version="1.0" encoding="utf-8"?> <EditText xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/field" android:layout_width="fill_parent" android:layout_height="fill_parent" android:singleLine="false" /> package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.EditText; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); EditText fld=(EditText)findViewById(R.id.field); fld.setText("java2s.com"); } }
Listen EditText event
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class Test extends Activity implements OnEditorActionListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); EditText text1 = (EditText) findViewById(R.id.text1); text1.setOnEditorActionListener(this); EditText text2 = (EditText) findViewById(R.id.text2); text2.setOnEditorActionListener(this); } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { return false; } } //main.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="fill_parent" android:orientation="vertical"> <EditText android:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionSearch" /> <EditText android:id="@+id/text2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionGo" /> </LinearLayout>
Create an EditText widget and add the watcher
package app.test; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; public class Test extends Activity implements TextWatcher { EditText text; int textCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); text = new EditText(this); text.addTextChangedListener(this); setContentView(text); } /* TextWatcher Implementation Methods */ public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int end) { textCount = text.getText().length(); setTitle(String.valueOf(textCount)); } public void afterTextChanged(Editable s) { } }
Get text from EditText
package app.test; import java.text.NumberFormat; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Test extends Activity { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); final EditText myEditField = (EditText) findViewById(R.id.mealprice); final TextView answerfield = (TextView) findViewById(R.id.answer); final Button button = (Button) findViewById(R.id.calculate); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { String mealprice = myEditField.getText().toString(); String answer = ""; if (mealprice.indexOf("$") == -1) { mealprice = "$" + mealprice; } NumberFormat nf = java.text.NumberFormat.getCurrencyInstance(); if (nf == null) { Log.i("", "NumberFormat is null"); } float fmp = nf.parse(mealprice).floatValue(); fmp *= 2; Log.i("", "Total:" + fmp); answer = "Full Price:" + nf.format(fmp); answerfield.setText(answer); } catch (java.text.ParseException pe) { Log.i("", "Parse exception caught"); answerfield.setText("Failed to parse amount?"); } catch (Exception e) { Log.e("", "Failed to Calculate Tip:" + e.getMessage()); e.printStackTrace(); answerfield.setText(e.getMessage()); } } }); } } // 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="Calculator" /> <EditText android:id="@+id/mealprice" android:layout_width="fill_parent" android:layout_height="wrap_content" android:autoText="true" /> <Button android:id="@+id/calculate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calculate Tip" /> <TextView android:id="@+id/answer" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> </LinearLayout>
Parse Uri from EditText control
package app.Test; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.widget.Button; import android.widget.EditText; public class appTest extends Activity { private EditText urlText; private Button goButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Get a handle to all user interface elements urlText = (EditText) findViewById(R.id.url_field); goButton = (Button) findViewById(R.id.go_button); // Setup event handlers goButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { openBrowser(); } }); urlText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View view, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { openBrowser(); return true; } return false; } }); } /** Open a browser on the URL specified in the text box */ private void openBrowser() { Uri uri = Uri.parse(urlText.getText().toString()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }