Android Tutorial - 20 UI exemple 2
1 - Window
Example of how to use a custom title android.view.Window#FEATURE_CUSTOM_TITLE.
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Test extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.row ); final TextView leftText = (TextView) findViewById(R.id.left_text); final TextView rightText = (TextView) findViewById(R.id.right_text); final EditText leftTextEdit = (EditText) findViewById(R.id.left_text_edit); final EditText rightTextEdit = (EditText) findViewById(R.id.right_text_edit); Button leftButton = (Button) findViewById(R.id.left_text_button); Button rightButton = (Button) findViewById(R.id.right_text_button); leftButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { leftText.setText(leftTextEdit.getText()); } }); rightButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { rightText.setText(rightTextEdit.getText()); } }); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen" 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:baselineAligned="false"> <EditText android:id="@+id/left_text_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxEms="10" android:minEms="10" android:layout_gravity="center_vertical" android:text="custom_title_left" /> <Button android:id="@+id/left_text_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="custom_title_left_button"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:baselineAligned="false"> <EditText android:id="@+id/right_text_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxEms="10" android:minEms="10" android:layout_gravity="center_vertical" android:text="custom_title_right" /> <Button android:id="@+id/right_text_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="custom_title_right_button"/> </LinearLayout> </LinearLayout> //row.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/left_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:text="custom_title_left" /> <TextView android:id="@+id/right_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="custom_title_right" /> </RelativeLayout>
2-ViewWrapper
Using ViewWrapper
package com.commonsware.android.fancylists.five; import android.view.View; import android.widget.ImageView; import android.widget.TextView; class ViewWrapper { View base; TextView label=null; ImageView icon=null; ViewWrapper(View base) { this.base=base; } TextView getLabel() { if (label==null) { label=(TextView)base.findViewById(R.id.label); } return(label); } ImageView getIcon() { if (icon==null) { icon=(ImageView)base.findViewById(R.id.icon); } return(icon); } } //src\com\commonsware\android\fancylists\five\ViewWrapperDemo.java package com.commonsware.android.fancylists.five; 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 ViewWrapperDemo 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); } private String getModel(int position) { return(((IconicAdapter)getListAdapter()).getItem(position)); } public void onListItemClick(ListView parent, View v, int position, long id) { selection.setText(getModel(position)); } class IconicAdapter extends ArrayAdapter<String> { IconicAdapter() { super(ViewWrapperDemo.this, R.layout.row, items); } public View getView(int position, View convertView,ViewGroup parent) { View row=convertView; ViewWrapper wrapper=null; if (row==null) { LayoutInflater inflater=getLayoutInflater(); row=inflater.inflate(R.layout.row, parent, false); wrapper=new ViewWrapper(row); row.setTag(wrapper); } else { wrapper=(ViewWrapper)row.getTag(); } wrapper.getLabel().setText(getModel(position)); if (getModel(position).length()>4) { wrapper.getIcon().setImageResource(R.drawable.delete); } else { wrapper.getIcon().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>
3-ViewFlipper
Using ViewFlipper
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ViewFlipper; public class Test extends Activity { ViewFlipper flipper; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); flipper=(ViewFlipper)findViewById(R.id.details); Button btn=(Button)findViewById(R.id.flip_me); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { flipper.showNext(); } }); } } //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/flip_me" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Flip Me!" /> <ViewFlipper android:id="@+id/details" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:textColor="#FF00FF00" android:text="This is the first panel" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:textColor="#FFFF0000" android:text="This is the second panel" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:textColor="#FFFFFF00" android:text="This is the third panel" /> </ViewFlipper> </LinearLayout>
Named ViewFlipper
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ViewFlipper; interface iViewFlipperListener{ void viewChangedTo(String name); } public class NamedViewFlipper extends ViewFlipper { private Map<View, String> myViewNames = new HashMap<View, String>(); private List<iViewFlipperListener> myListeners = new ArrayList<iViewFlipperListener>(); public NamedViewFlipper( Context aContext ) { super( aContext ); } public NamedViewFlipper( Context aContext, AttributeSet aAttrs ) { super( aContext, aAttrs ); } public void setNameForView(View aView, String aName){ myViewNames.put(aView, aName); } public String getCurrentViewName(){ return myViewNames.get(getCurrentView()); } public void flipToView(String aName){ while(!getCurrentViewName().equals( aName )){ super.showNext(); } notifyListeners(); } @Override public void showNext() { super.showNext(); notifyListeners(); } @Override public void showPrevious() { super.showPrevious(); notifyListeners(); } @Override public void setDisplayedChild( int aWhichChild ) { super.setDisplayedChild( aWhichChild ); notifyListeners(); } private void notifyListeners() { String theCurrentViewName = getCurrentViewName(); for(iViewFlipperListener theListener : myListeners){ theListener.viewChangedTo( theCurrentViewName ); } } public void addViewFlipperListener(iViewFlipperListener aListener){ myListeners.add(aListener); } public void removeViewFlipperListener(iViewFlipperListener aListener){ myListeners.remove( aListener ); } }
4-TextWatcher
Convert input value to Currency in TextWatcher
package app.test; import java.text.NumberFormat; import android.text.Editable; import android.text.TextWatcher; import android.app.Activity; import android.os.Bundle; import android.widget.EditText; public class Test extends Activity { EditText text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); text = new EditText(this); text.addTextChangedListener(new CurrencyTextWatcher()); setContentView(text); } } class CurrencyTextWatcher implements TextWatcher { boolean mEditing; public CurrencyTextWatcher() { mEditing = false; } public synchronized void afterTextChanged(Editable s) { if(!mEditing) { mEditing = true; String digits = s.toString().replaceAll("\\D", ""); NumberFormat nf = NumberFormat.getCurrencyInstance(); try{ String formatted = nf.format(Double.parseDouble(digits)/100); s.replace(0, s.length(), formatted); } catch (NumberFormatException nfe) { s.clear(); } mEditing = false; } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }
Text input listener
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) { } }
5-TextSwitcher
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.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.ViewSwitcher; /** * Uses a TextSwitcher. */ public class TextSwitcher1 extends Activity implements ViewSwitcher.ViewFactory, View.OnClickListener { private TextSwitcher mSwitcher; private int mCounter = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_switcher_1); mSwitcher = (TextSwitcher) findViewById(R.id.switcher); mSwitcher.setFactory(this); Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in); Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out); mSwitcher.setInAnimation(in); mSwitcher.setOutAnimation(out); Button nextButton = (Button) findViewById(R.id.next); nextButton.setOnClickListener(this); updateCounter(); } public void onClick(View v) { mCounter++; updateCounter(); } private void updateCounter() { mSwitcher.setText(String.valueOf(mCounter)); } public View makeView() { TextView t = new TextView(this); t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL); t.setTextSize(36); return t; } } //layout/text_switcher_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"> <Button android:id="@+id/next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/text_switcher_1_next_text" /> <TextSwitcher android:id="@+id/switcher" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
6-TabActivity
package app.test; import android.app.Activity; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.webkit.WebView; import android.widget.TabHost; class AndroidBrowser extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); browser = new WebView(this); setContentView(browser); browser.loadUrl("http://www.android.com/"); } } class CWBrowser extends Activity { WebView browser; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); browser = new WebView(this); setContentView(browser); browser.loadUrl("http://java2s.com"); } } public class Test extends TabActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TabHost host = getTabHost(); host.addTab(host.newTabSpec("one").setIndicator("CW") .setContent(new Intent(this, CWBrowser.class))); host.addTab(host.newTabSpec("two").setIndicator("Android") .setContent(new Intent(this, AndroidBrowser.class))); } } //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, IntentTabDemo" /> </LinearLayout>
Thread demo
package apt.tutorial; import android.app.TabActivity; import android.os.Bundle; import android.os.SystemClock; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.view.Window; 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 android.widget.Toast; 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; EditText notes=null; RadioGroup types=null; Restaurant current=null; int progress=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.main); name=(EditText)findViewById(R.id.name); address=(EditText)findViewById(R.id.addr); notes=(EditText)findViewById(R.id.notes); 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); } @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option, menu); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.toast) { String message="No restaurant selected"; if (current!=null) { message=current.getNotes(); } Toast.makeText(this, message, Toast.LENGTH_LONG).show(); return(true); } else if (item.getItemId()==R.id.run) { setProgressBarVisibility(true); progress=0; new Thread(longTask).start(); return(true); } return(super.onOptionsItemSelected(item)); } private void doSomeLongWork(final int incr) { runOnUiThread(new Runnable() { public void run() { progress+=incr; setProgress(progress); } }); SystemClock.sleep(250); // should be something more useful! } private View.OnClickListener onSave=new View.OnClickListener() { public void onClick(View v) { current=new Restaurant(); current.setName(name.getText().toString()); current.setAddress(address.getText().toString()); current.setNotes(notes.getText().toString()); switch (types.getCheckedRadioButtonId()) { case R.id.sit_down: current.setType("sit_down"); break; case R.id.take_out: current.setType("take_out"); break; case R.id.delivery: current.setType("delivery"); break; } adapter.add(current); } }; private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { current=model.get(position); name.setText(current.getName()); address.setText(current.getAddress()); notes.setText(current.getNotes()); if (current.getType().equals("sit_down")) { types.check(R.id.sit_down); } else if (current.getType().equals("take_out")) { types.check(R.id.take_out); } else { types.check(R.id.delivery); } getTabHost().setCurrentTab(1); } }; private Runnable longTask=new Runnable() { public void run() { for (int i=0;i<20;i++) { doSomeLongWork(500); } runOnUiThread(new Runnable() { public void run() { setProgressBarVisibility(false); } }); } }; 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=""; private String notes=""; 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 getNotes() { return(notes); } public void setNotes(String notes) { this.notes=notes; } public String toString() { return(getName()); } } //strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LunchList</string> </resources> //option.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/toast" android:title="Raise Toast" android:icon="@drawable/toast" /> <item android:id="@+id/run" android:title="Run Long Task" android:icon="@drawable/run" /> </menu> //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> <TableRow> <TextView android:text="Notes:" /> <EditText android:id="@+id/notes" android:singleLine="false" android:gravity="top" android:lines="2" android:scrollHorizontally="false" android:maxLines="2" android:maxWidth="200sp" /> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout> </FrameLayout> </LinearLayout> </TabHost> //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>
7-SlidingDrawer
Set handle and content for SlidingDrawer
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>
Set orientation for SlidingDrawer
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>
8-ScrollView
Create scrollable panel with ScrollView
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>
Demonstrates scrolling with a ScrollView.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class ScrollBar2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scrollbar2); } } //layout/scrollbar2.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. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbarTrackVertical="@drawable/scrollbar_vertical_track" android:scrollbarThumbVertical="@drawable/scrollbar_vertical_thumb" android:scrollbarSize="12dip"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <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"/> <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"/> <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"/> <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>
Scrolling with a ScrollView
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; public class ScrollBar1 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scrollbar1); } } //layout/scrollbar1.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. --> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="scrollbar_1_text"/> </LinearLayout> </ScrollView>
how a well behaved view with internal selection InternalSelectionView can cause its parent android.widget.ScrollView to scroll to keep the internally interesting rectangle on the screen.
package com.example.android.apis.view; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ScrollView; public class InternalSelectionScroll extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ScrollView sv = new ScrollView(this); ViewGroup.LayoutParams svLp = new ScrollView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); LinearLayout ll = new LinearLayout(this); ll.setLayoutParams(svLp); sv.addView(ll); InternalSelectionView isv = new InternalSelectionView(this, 10); int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); LinearLayout.LayoutParams llLp = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 2 * screenHeight); // 2x screen height to ensure scrolling isv.setLayoutParams(llLp); ll.addView(isv); setContentView(sv); } } package com.example.android.apis.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; public class InternalSelectionView extends View { private Paint mPainter = new Paint(); private Paint mTextPaint = new Paint(); private Rect mTempRect = new Rect(); private int mNumRows = 5; private int mSelectedRow = 0; private final int mEstimatedPixelHeight = 10; private Integer mDesiredHeight = null; private String mLabel = null; public InternalSelectionView(Context context, int numRows) { this(context, numRows, ""); } public InternalSelectionView(Context context, int numRows, String label) { super(context); mNumRows = numRows; mLabel = label; init(); } public InternalSelectionView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setFocusable(true); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(10); mTextPaint.setColor(Color.WHITE); } public int getNumRows() { return mNumRows; } public int getSelectedRow() { return mSelectedRow; } public void setDesiredHeight(int desiredHeight) { mDesiredHeight = desiredHeight; } public String getLabel() { return mLabel; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension( measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } private int measureWidth(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); int desiredWidth = 300 + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be return specSize; } else if (specMode == MeasureSpec.AT_MOST) { return desiredWidth < specSize ? desiredWidth : specSize; } else { return desiredWidth; } } private int measureHeight(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); int desiredHeight = mDesiredHeight != null ? mDesiredHeight : mNumRows * mEstimatedPixelHeight + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be return specSize; } else if (specMode == MeasureSpec.AT_MOST) { return desiredHeight < specSize ? desiredHeight : specSize; } else { return desiredHeight; } } @Override protected void onDraw(Canvas canvas) { int rowHeight = getRowHeight(); int rectTop = getPaddingTop(); int rectLeft = getPaddingLeft(); int rectRight = getWidth() - getPaddingRight(); for (int i = 0; i < mNumRows; i++) { mPainter.setColor(Color.BLACK); mPainter.setAlpha(0x20); // draw background rect mTempRect.set(rectLeft, rectTop, rectRight, rectTop + rowHeight); canvas.drawRect(mTempRect, mPainter); // draw forground rect if (i == mSelectedRow && hasFocus()) { mPainter.setColor(Color.RED); mPainter.setAlpha(0xF0); mTextPaint.setAlpha(0xFF); } else { mPainter.setColor(Color.BLACK); mPainter.setAlpha(0x40); mTextPaint.setAlpha(0xF0); } mTempRect.set(rectLeft + 2, rectTop + 2, rectRight - 2, rectTop + rowHeight - 2); canvas.drawRect(mTempRect, mPainter); // draw text to help when visually inspecting canvas.drawText( Integer.toString(i), rectLeft + 2, rectTop + 2 - (int) mTextPaint.ascent(), mTextPaint); rectTop += rowHeight; } } private int getRowHeight() { return (getHeight() - getPaddingTop() - getPaddingBottom()) / mNumRows; } public void getRectForRow(Rect rect, int row) { final int rowHeight = getRowHeight(); final int top = getPaddingTop() + row * rowHeight; rect.set(getPaddingLeft(), top, getWidth() - getPaddingRight(), top + rowHeight); } void ensureRectVisible() { getRectForRow(mTempRect, mSelectedRow); requestRectangleOnScreen(mTempRect); } /* (non-Javadoc) * @see android.view.KeyEvent.Callback#onKeyDown(int, android.view.KeyEvent) */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_UP: if (mSelectedRow > 0) { mSelectedRow--; invalidate(); ensureRectVisible(); return true; } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mSelectedRow < (mNumRows - 1)) { mSelectedRow++; invalidate(); ensureRectVisible(); return true; } break; } return false; } @Override public void getFocusedRect(Rect r) { getRectForRow(r, mSelectedRow); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); if (focused) { switch (direction) { case View.FOCUS_DOWN: mSelectedRow = 0; break; case View.FOCUS_UP: mSelectedRow = mNumRows - 1; break; case View.FOCUS_LEFT: // fall through case View.FOCUS_RIGHT: // set the row that is closest to the rect if (previouslyFocusedRect != null) { int y = previouslyFocusedRect.top + (previouslyFocusedRect.height() / 2); int yPerRow = getHeight() / mNumRows; mSelectedRow = y / yPerRow; } else { mSelectedRow = 0; } break; default: // can't gleam any useful information about what internal // selection should be... return; } invalidate(); } } @Override public String toString() { if (mLabel != null) { return mLabel; } return super.toString(); } }
Using HorizontalScrollView
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 HorizontalScrollView1 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.horizontal_scroll_view1); } } //horizontal_scroll_view1.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. --> <!-- Demonstrates horizontal scrolling with a ScrollView. --> <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dip" android:layout_height="120dip"> <TextView android:layout_width="300dip" android:layout_height="wrap_content" android:text="scrollbar_3_text" /> </HorizontalScrollView>
9-RelativeLayout
Use RelativeLayout to hold ImageView and AnalogClock
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>
Relative layout demo
package app.test; import android.app.Activity; import android.os.Bundle; 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"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/icon" android:padding="10dip"> <TextView android:id="@+id/label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="UserName" /> <EditText android:id="@+id/entry" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@android:drawable/editbox_background" android:layout_below="@id/label" /> <Button android:id="@+id/cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/entry" android:layout_alignParentRight="true" android:layout_marginLeft="10dip" android:text="Cancel" /> <Button android:id="@+id/ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/cancel" android:layout_alignTop="@id/cancel" android:text="OK" /> </RelativeLayout>
Adding SlidingDrawer to RelativeLayout
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>
10-PreferenceActivity
Using PreferenceActivity
package apt.tutorial; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; public class DetailForm extends Activity { EditText name=null; EditText address=null; EditText notes=null; RadioGroup types=null; RestaurantHelper helper=null; String restaurantId=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail_form); helper=new RestaurantHelper(this); name=(EditText)findViewById(R.id.name); address=(EditText)findViewById(R.id.addr); notes=(EditText)findViewById(R.id.notes); types=(RadioGroup)findViewById(R.id.types); Button save=(Button)findViewById(R.id.save); save.setOnClickListener(onSave); restaurantId=getIntent().getStringExtra(LunchList.ID_EXTRA); if (restaurantId!=null) { load(); } } @Override public void onDestroy() { super.onDestroy(); helper.close(); } private void load() { Cursor c=helper.getById(restaurantId); c.moveToFirst(); name.setText(helper.getName(c)); address.setText(helper.getAddress(c)); notes.setText(helper.getNotes(c)); if (helper.getType(c).equals("sit_down")) { types.check(R.id.sit_down); } else if (helper.getType(c).equals("take_out")) { types.check(R.id.take_out); } else { types.check(R.id.delivery); } c.close(); } private View.OnClickListener onSave=new View.OnClickListener() { public void onClick(View v) { String type=null; switch (types.getCheckedRadioButtonId()) { case R.id.sit_down: type="sit_down"; break; case R.id.take_out: type="take_out"; break; case R.id.delivery: type="delivery"; break; } if (restaurantId==null) { helper.insert(name.getText().toString(), address.getText().toString(), type, notes.getText().toString()); } else { helper.update(restaurantId, name.getText().toString(), address.getText().toString(), type, notes.getText().toString()); } finish(); } }; } package apt.tutorial; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } package apt.tutorial; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class LunchList extends ListActivity { public final static String ID_EXTRA="apt.tutorial._ID"; Cursor model=null; RestaurantAdapter adapter=null; RestaurantHelper helper=null; SharedPreferences prefs=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); helper=new RestaurantHelper(this); prefs=PreferenceManager.getDefaultSharedPreferences(this); initList(); prefs.registerOnSharedPreferenceChangeListener(prefListener); } @Override public void onDestroy() { super.onDestroy(); helper.close(); } @Override public void onListItemClick(ListView list, View view, int position, long id) { Intent i=new Intent(LunchList.this, DetailForm.class); i.putExtra(ID_EXTRA, String.valueOf(id)); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option, menu); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId()==R.id.add) { startActivity(new Intent(LunchList.this, DetailForm.class)); return(true); } else if (item.getItemId()==R.id.prefs) { startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } private void initList() { if (model!=null) { stopManagingCursor(model); model.close(); } model=helper.getAll(prefs.getString("sort_order", "name")); startManagingCursor(model); adapter=new RestaurantAdapter(model); setListAdapter(adapter); } private SharedPreferences.OnSharedPreferenceChangeListener prefListener= new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String key) { if (key.equals("sort_order")) { initList(); } } }; class RestaurantAdapter extends CursorAdapter { RestaurantAdapter(Cursor c) { super(LunchList.this, c); } @Override public void bindView(View row, Context ctxt, Cursor c) { RestaurantHolder holder=(RestaurantHolder)row.getTag(); holder.populateFrom(c, helper); } @Override public View newView(Context ctxt, Cursor c, ViewGroup parent) { LayoutInflater inflater=getLayoutInflater(); View row=inflater.inflate(R.layout.row, parent, false); RestaurantHolder holder=new RestaurantHolder(row); row.setTag(holder); 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(Cursor c, RestaurantHelper helper) { name.setText(helper.getName(c)); address.setText(helper.getAddress(c)); if (helper.getType(c).equals("sit_down")) { icon.setImageResource(R.drawable.ball_red); } else if (helper.getType(c).equals("take_out")) { icon.setImageResource(R.drawable.ball_yellow); } else { icon.setImageResource(R.drawable.ball_green); } } } } package apt.tutorial; import android.content.Context; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; class RestaurantHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME="lunchlist.db"; private static final int SCHEMA_VERSION=1; public RestaurantHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // no-op, since will not be called until 2nd schema // version exists } public Cursor getAll(String orderBy) { return(getReadableDatabase() .rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY "+orderBy, null)); } public Cursor getById(String id) { String[] args={id}; return(getReadableDatabase() .rawQuery("SELECT _id, name, address, type, notes FROM restaurants WHERE _ID=?", args)); } public void insert(String name, String address, String type, String notes) { ContentValues cv=new ContentValues(); cv.put("name", name); cv.put("address", address); cv.put("type", type); cv.put("notes", notes); getWritableDatabase().insert("restaurants", "name", cv); } public void update(String id, String name, String address, String type, String notes) { ContentValues cv=new ContentValues(); String[] args={id}; cv.put("name", name); cv.put("address", address); cv.put("type", type); cv.put("notes", notes); getWritableDatabase().update("restaurants", cv, "_ID=?", args); } public String getName(Cursor c) { return(c.getString(1)); } public String getAddress(Cursor c) { return(c.getString(2)); } public String getType(Cursor c) { return(c.getString(3)); } public String getNotes(Cursor c) { return(c.getString(4)); } } //xml/preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <ListPreference android:key="sort_order" android:title="Sort Order" android:summary="Choose the order the list uses" android:entries="@array/sort_names" android:entryValues="@array/sort_clauses" android:dialogTitle="Choose a sort order" /> </PreferenceScreen> //values/arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="sort_names"> <item>By Name, Ascending</item> <item>By Name, Descending</item> <item>By Type</item> <item>By Address, Ascending</item> <item>By Address, Descending</item> </string-array> <string-array name="sort_clauses"> <item>name ASC</item> <item>name DESC</item> <item>type, name ASC</item> <item>address ASC</item> <item>address DESC</item> </string-array> </resources> //values/strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">LunchList</string> </resources> //menu/option.xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/add" android:title="Add" android:icon="@drawable/ic_menu_add" /> <item android:id="@+id/prefs" android:title="Settings" android:icon="@drawable/ic_menu_preferences" /> </menu> //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" /> //layout/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> //layout/detail_form.xml <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" 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> <TableRow> <TextView android:text="Notes:" /> <EditText android:id="@+id/notes" android:singleLine="false" android:gravity="top" android:lines="2" android:scrollHorizontally="false" android:maxLines="2" android:maxWidth="200sp" /> </TableRow> <Button android:id="@+id/save" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" /> </TableLayout>
Manager Preference with PreferenceActivity
package app.test; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import android.os.Bundle; import android.preference.PreferenceActivity; class FlightPreferenceActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.main); } } public class Test extends Activity { private Resources resources; private SharedPreferences prefs; private TextView tv = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); resources = this.getResources(); prefs = PreferenceManager.getDefaultSharedPreferences(this); PreferenceManager.setDefaultValues(this, R.xml.main, false); tv = (TextView)findViewById(R.id.text1); setOptionText(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.my_menu, menu); return true; } @Override public boolean onOptionsItemSelected (MenuItem item) { if (item.getItemId() == R.id.menu_prefs) { Intent intent = new Intent() .setClass(this, FlightPreferenceActivity.class); this.startActivityForResult(intent, 0); } return true; } @Override public void onActivityResult(int reqCode, int resCode, Intent data) { super.onActivityResult(reqCode, resCode, data); setOptionText(); } private void setOptionText() { String option = prefs.getString("", null); String[] optionText = new String[]{}; tv.setText(option + " (" +optionText[Integer.parseInt(option)] + ")"); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="flight_columns_pref" android:title="Flight Search Preferences" android:summary="Set Columns for Search Results"> <CheckBoxPreference android:key="show_airline_column_pref" android:title="Airline" android:summary="Show Airline column" /> <CheckBoxPreference android:key="show_departure_column_pref" android:title="Departure" android:summary="Show Departure column" /> <CheckBoxPreference android:key="show_arrival_column_pref" android:title="Arrival" android:summary="Show Arrival column" /> <CheckBoxPreference android:key="show_total_travel_time_column_pref" android:title="Total Travel Time" android:summary="Show Total Travel Time column" /> <CheckBoxPreference android:key="show_price_column_pref" android:title="Price" android:summary="Show Price column" /> </PreferenceScreen> //my_menu.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/menu/mainmenu.xml --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_prefs" android:title="@string/menu_prefs_title" /> </menu> //xml/main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:text="" android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
PreferenceActivity demo
package com.commonsware.android.prefdialogs; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class DialogsDemo extends Activity { private static final int EDIT_ID = Menu.FIRST+2; private TextView checkbox=null; private TextView ringtone=null; private TextView checkbox2=null; private TextView text=null; private TextView list=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); checkbox=(TextView)findViewById(R.id.checkbox); ringtone=(TextView)findViewById(R.id.ringtone); checkbox2=(TextView)findViewById(R.id.checkbox2); text=(TextView)findViewById(R.id.text); list=(TextView)findViewById(R.id.list); } @Override public void onResume() { super.onResume(); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false)).toString()); ringtone.setText(prefs.getString("ringtone", "<unset>")); checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false)).toString()); text.setText(prefs.getString("text", "<unset>")); list.setText(prefs.getString("list", "<unset>")); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Edit Prefs") .setIcon(R.drawable.misc) .setAlphabeticShortcut('e'); return(super.onCreateOptionsMenu(menu)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case EDIT_ID: startActivity(new Intent(this, EditPreferences.class)); return(true); } return(super.onOptionsItemSelected(item)); } } //src\com\commonsware\android\prefdialogs\EditPreferences.java package com.commonsware.android.prefdialogs; import android.app.Activity; import android.os.Bundle; import android.preference.PreferenceActivity; public class EditPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } //res\layout\main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TableRow> <TextView android:text="Checkbox:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox" /> </TableRow> <TableRow> <TextView android:text="Ringtone:" android:paddingRight="5px" /> <TextView android:id="@+id/ringtone" /> </TableRow> <TableRow> <TextView android:text="Checkbox #2:" android:paddingRight="5px" /> <TextView android:id="@+id/checkbox2" /> </TableRow> <TableRow> <TextView android:text="Text:" android:paddingRight="5px" /> <TextView android:id="@+id/text" /> </TableRow> <TableRow> <TextView android:text="List Selection:" android:paddingRight="5px" /> <TextView android:id="@+id/list" /> </TableRow> </TableLayout> //res\values\arrays.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="cities"> <item>Philadelphia</item> <item>Pittsburgh</item> <item>Allentown/Bethlehem</item> <item>Erie</item> <item>Reading</item> <item>Scranton</item> <item>Lancaster</item> <item>Altoona</item> <item>Harrisburg</item> </string-array> <string-array name="airport_codes"> <item>PHL</item> <item>PIT</item> <item>ABE</item> <item>ERI</item> <item>RDG</item> <item>AVP</item> <item>LNS</item> <item>AOO</item> <item>MDT</item> </string-array> </resources> //res\values\strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">DialogsDemo</string> <string name="checkbox">checkbox</string> <string name="ringtone">ringtone</string> <string name="checkbox2">checkbox2</string> <string name="text">text</string> <string name="list">list</string> </resources> //res\xml\preferences.xml <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="Simple Preferences"> <CheckBoxPreference android:key="checkbox" android:title="Checkbox Preference" android:summary="Check it on, check it off" /> <RingtonePreference android:key="ringtone" android:title="Ringtone Preference" android:showDefault="true" android:showSilent="true" android:summary="Pick a tone, any tone" /> </PreferenceCategory> <PreferenceCategory android:title="Detail Screens"> <PreferenceScreen android:key="detail" android:title="Detail Screen" android:summary="Additional preferences held in another page"> <CheckBoxPreference android:key="checkbox2" android:title="Another Checkbox" android:summary="On. Off. It really doesn't matter." /> </PreferenceScreen> </PreferenceCategory> <PreferenceCategory android:title="Other Preferences"> <EditTextPreference android:key="text" android:title="Text Entry Dialog" android:summary="Click to pop up a field for entry" android:dialogTitle="Enter something useful" /> <ListPreference android:key="list" android:title="Selection Dialog" android:summary="Click to pop up a list to choose from" android:entries="@array/cities" android:entryValues="@array/airport_codes" android:dialogTitle="Choose a Pennsylvania city" /> </PreferenceCategory> </PreferenceScreen>
11-MapView
extends MapView
//package djrain.lilochat.client; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.View; import com.google.android.maps.MapView; public class LiloMapView extends MapView { GestureDetector gd; private OnLongClickListener onLongClickListener = new OnLongClickListener() { public boolean onLongClick(View v) { Log.e("djrain", "OnLongClickListener onLongClick:"); return false; } }; public LiloMapView(Context context, AttributeSet attrs) { super(context, attrs); setBuiltInZoomControls(true); this.setLongClickable(true); this.setClickable(true); Log.e("djrain", "OnLongClickListener isLongClickable():" + isLongClickable()); setOnLongClickListener(onLongClickListener); gd = new GestureDetector(gestureListener); } OnGestureListener gestureListener = new OnGestureListener() { public boolean onSingleTapUp(MotionEvent e) { Log.i("djrain", "onSingleTapUp:"+e); return false; } public void onShowPress(MotionEvent e) { Log.i("djrain", "onShowPress:"+e); } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.i("djrain", "onScroll:"+e2); return false; } public void onLongPress(MotionEvent e) { LiloGeocoder geo = new LiloGeocoder(getContext()); double [] lalo = new double[2]; LocationHelper.pixel2lalo(LiloMapView.this , e , lalo); geo.getAddress(lalo); Log.i("djrain", "onLongPress:"+e); } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.i("djrain", "onFling:"+e2); return false; } public boolean onDown(MotionEvent e) { Log.i("djrain", "onDown:"+e); return false; } }; @Override public boolean onTouchEvent(MotionEvent ev) { gd.onTouchEvent(ev); return super.onTouchEvent(ev); } }
Google map view
import android.os.Bundle; import android.view.View; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; public class MapViewDemoActivity extends MapActivity { private MapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapview); mapView = (MapView)findViewById(R.id.mapview); } public void myClickHandler(View target) { switch(target.getId()) { case R.id.zoomin: mapView.getController().zoomIn(); break; case R.id.zoomout: mapView.getController().zoomOut(); break; case R.id.sat: mapView.setSatellite(true); break; case R.id.street: mapView.setStreetView(true); break; case R.id.traffic: mapView.setTraffic(true); break; case R.id.normal: mapView.setSatellite(false); mapView.setStreetView(false); mapView.setTraffic(false); break; default: break; } mapView.postInvalidateDelayed(2000); } @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } } <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/layout/mapview.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:id="@+id/zoomin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:onClick="myClickHandler" android:padding="12px" /> <Button android:id="@+id/zoomout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:onClick="myClickHandler" android:padding="12px" /> <Button android:id="@+id/sat" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Satellite" android:onClick="myClickHandler" android:padding="8px" /> <Button android:id="@+id/street" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Street" android:onClick="myClickHandler" android:padding="8px" /> <Button android:id="@+id/traffic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Traffic" android:onClick="myClickHandler" android:padding="8px" /> <Button android:id="@+id/normal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Normal" android:onClick="myClickHandler" android:padding="8px" /> </LinearLayout> <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="true" android:apiKey="yourKey" /> </LinearLayout>
12-ListPreference
package app.test; import android.os.Bundle; import android.preference.PreferenceActivity; public class Test extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.main); } } //xml/main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is /res/xml/mypreferences.xml --> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="flight_option_preference" android:title="@string/prefTitle" android:summary="@string/prefSummary"> <ListPreference android:key="@string/selected_flight_sort_option" android:title="@string/listTitle" android:summary="@string/listSummary" android:entries="@array/flight_sort_options" android:entryValues="@array/flight_sort_options_values" android:dialogTitle="@string/dialogTitle" android:defaultValue="@string/flight_sort_option_default_value" /> </PreferenceScreen>
13-ImageSwitcher
Using ImageSwitcher and Gallery
package app.test; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher.ViewFactory; public class Test extends Activity implements ViewFactory { Integer[] imageIDs = { R.drawable.icon, R.drawable.icon, }; private ImageSwitcher imageSwitcher; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1); imageSwitcher.setFactory(this); imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left)); imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right)); 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) { imageSwitcher.setImageResource(imageIDs[position]); } }); } public View makeView() { ImageView imageView = new ImageView(this); imageView.setBackgroundColor(0xFF000000); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setLayoutParams(new ImageSwitcher.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); return imageView; } public class ImageAdapter extends BaseAdapter { private Context context; private int itemBackground; public ImageAdapter(Context c) { context = c; TypedArray a = obtainStyledAttributes(R.styleable.Gallery1); itemBackground = a.getResourceId( R.styleable.Gallery1_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return imageIDs.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 = 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"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff000000" > <ImageSwitcher android:id="@+id/switcher1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" /> <Gallery android:id="@+id/gallery1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout>
Using ImageSwitcher
package com.example.android.apis.view; import com.example.android.apis.R; 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.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ViewSwitcher; public class ImageSwitcher1 extends Activity implements AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.image_switcher_1); 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.MATCH_PARENT, LayoutParams.MATCH_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.picture_frame); return i; } private Context mContext; } private Integer[] mThumbIds = { R.drawable.sample_thumb_0, R.drawable.sample_thumb_1, R.drawable.sample_thumb_2, R.drawable.sample_thumb_3, R.drawable.sample_thumb_4, R.drawable.sample_thumb_5, R.drawable.sample_thumb_6, R.drawable.sample_thumb_7}; private Integer[] mImageIds = { R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7}; } //image_switcher_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. --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageSwitcher android:id="@+id/switcher" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" /> <Gallery android:id="@+id/gallery" android:background="#55000000" android:layout_width="match_parent" android:layout_height="60dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center_vertical" android:spacing="16dp" /> </RelativeLayout>
Using ImageSwitcher and CheckBox
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>
14-Fragment
FragmentDialog Or Activity
package com.example.android.apis.app; import com.example.android.apis.R; import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class FragmentDialogOrActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_dialog_or_activity); if (savedInstanceState == null) { // First-time init; create fragment to embed in activity. FragmentTransaction ft = getFragmentManager().beginTransaction(); DialogFragment newFragment = MyDialogFragment.newInstance(); ft.add(R.id.embedded, newFragment); ft.commit(); } // Watch for button clicks. Button button = (Button)findViewById(R.id.show_dialog); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { showDialog(); } }); } void showDialog() { // Create the fragment and show it as a dialog. DialogFragment newFragment = MyDialogFragment.newInstance(); newFragment.show(getFragmentManager(), "dialog"); } public static class MyDialogFragment extends DialogFragment { static MyDialogFragment newInstance() { return new MyDialogFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.hello_world, container, false); View tv = v.findViewById(R.id.text); ((TextView)tv).setText("This is an instance of MyDialogFragment"); return v; } } } //fragment_dialog_or_activity.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Top-level content view for the simple fragment sample. --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip" android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:layout_gravity="center_vertical|center_horizontal" android:gravity="top|center_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" android:text="@string/fragment_dialog_or_activity_msg" /> <Button android:id="@+id/show_dialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:text="@string/show"> <requestFocus /> </Button> <View android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> <TextView android:id="@+id/inline_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:layout_gravity="center_vertical|center_horizontal" android:textAppearance="?android:attr/textAppearanceMedium" android:text="@string/fragment_dialog_or_activity_inline" /> <FrameLayout android:id="@+id/embedded" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:layout_gravity="center_vertical|center_horizontal" android:padding="6dp" android:background="#ff303030" android:gravity="top|center_horizontal" /> </LinearLayout>
Demonstration of using fragments to implement different activity layouts.
package com.example.android.apis.app; import com.example.android.apis.R; import com.example.android.apis.Shakespeare; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.ListFragment; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ScrollView; import android.widget.TextView; /** * Demonstration of using fragments to implement different activity layouts. * This sample provides a different layout (and activity flow) when run in * landscape. */ public class FragmentLayout extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_layout); } /** * This is a secondary activity, to show what the user has selected * when the screen is not large enough to show it all in one activity. */ public static class DetailsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // If the screen is now in landscape mode, we can show the // dialog in-line with the list so we don't need this activity. finish(); return; } if (savedInstanceState == null) { // During initial setup, plug in the details fragment. DetailsFragment details = new DetailsFragment(); details.setArguments(getIntent().getExtras()); getFragmentManager().beginTransaction().add(android.R.id.content, details).commit(); } } } /** * This is the "top-level" fragment, showing a list of items that the * user can pick. Upon picking an item, it takes care of displaying the * data to the user as appropriate based on the currrent UI layout. */ public static class TitlesFragment extends ListFragment { boolean mDualPane; int mCurCheckPosition = 0; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Populate list with our static array of titles. setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES)); // Check to see if we have a frame in which to embed the details // fragment directly in the containing UI. View detailsFrame = getActivity().findViewById(R.id.details); mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE; if (savedInstanceState != null) { // Restore last state for checked position. mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); } if (mDualPane) { // In dual-pane mode, the list view highlights the selected item. getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Make sure our UI is in the correct state. showDetails(mCurCheckPosition); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("curChoice", mCurCheckPosition); } @Override public void onListItemClick(ListView l, View v, int position, long id) { showDetails(position); } /** * Helper function to show the details of a selected item, either by * displaying a fragment in-place in the current UI, or starting a * whole new activity in which it is displayed. */ void showDetails(int index) { mCurCheckPosition = index; if (mDualPane) { // We can display everything in-place with fragments, so update // the list to highlight the selected item and show the data. getListView().setItemChecked(index, true); // Check what fragment is currently shown, replace if needed. DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details); if (details == null || details.getShownIndex() != index) { // Make new fragment to show this selection. details = DetailsFragment.newInstance(index); // Execute a transaction, replacing any existing fragment // with this one inside the frame. FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.details, details); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } else { // Otherwise we need to launch a new activity to display // the dialog fragment with selected text. Intent intent = new Intent(); intent.setClass(getActivity(), DetailsActivity.class); intent.putExtra("index", index); startActivity(intent); } } } /** * This is the secondary fragment, displaying the details of a particular * item. */ public static class DetailsFragment extends Fragment { /** * Create a new instance of DetailsFragment, initialized to * show the text at 'index'. */ public static DetailsFragment newInstance(int index) { DetailsFragment f = new DetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt("index", index); f.setArguments(args); return f; } public int getShownIndex() { return getArguments().getInt("index", 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { // We have different layouts, and in one of them this // fragment's containing frame doesn't exist. The fragment // may still be created from its saved state, but there is // no reason to try to create its view hierarchy because it // won't be displayed. Note this is not needed -- we could // just run the code below, where we would create and return // the view hierarchy; it would just never be used. return null; } ScrollView scroller = new ScrollView(getActivity()); TextView text = new TextView(getActivity()); int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources().getDisplayMetrics()); text.setPadding(padding, padding, padding, padding); scroller.addView(text); text.setText(Shakespeare.DIALOGUE[getShownIndex()]); return scroller; } } } package com.example.android.apis; public final class Shakespeare { /** * Our data, part 1. */ public static final String[] TITLES = { "Henry IV (1)", "Henry V", "Henry VIII", "Richard II", "Richard III", "Merchant of Venice", "Othello", "King Lear" }; /** * Our data, part 2. */ public static final String[] DIALOGUE = { "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!" }; } //fragment_layout.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Top-level content view for the layout fragment sample. This version is for display when not in landscape: we can only fit the list of titles. --> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment" android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout>
15-Drag Drop
Draggable dot
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.os.Bundle; import android.view.DragEvent; import android.view.View; import android.widget.TextView; import android.content.ClipData; import android.content.Context; import android.content.res.TypedArray; import android.graphics.*; import android.os.SystemClock; import android.text.TextPaint; import android.util.AttributeSet; import android.util.Log; import android.view.DragEvent; import android.view.View; import android.widget.TextView; class DraggableDot extends View { static final String TAG = "DraggableDot"; private boolean mDragInProgress; private boolean mHovering; private boolean mAcceptsDrag; TextView mReportView; private Paint mPaint; private TextPaint mLegendPaint; private Paint mGlow; private static final int NUM_GLOW_STEPS = 10; private static final int GREEN_STEP = 0x0000FF00 / NUM_GLOW_STEPS; private static final int WHITE_STEP = 0x00FFFFFF / NUM_GLOW_STEPS; private static final int ALPHA_STEP = 0xFF000000 / NUM_GLOW_STEPS; int mRadius; int mAnrType; CharSequence mLegend; static final int ANR_NONE = 0; static final int ANR_SHADOW = 1; static final int ANR_DROP = 2; void sleepSixSeconds() { // hang forever; good for producing ANRs long start = SystemClock.uptimeMillis(); do { try { Thread.sleep(1000); } catch (InterruptedException e) {} } while (SystemClock.uptimeMillis() < start + 6000); } // Shadow builder that can ANR if desired class ANRShadowBuilder extends DragShadowBuilder { boolean mDoAnr; public ANRShadowBuilder(View view, boolean doAnr) { super(view); mDoAnr = doAnr; } @Override public void onDrawShadow(Canvas canvas) { if (mDoAnr) { sleepSixSeconds(); } super.onDrawShadow(canvas); } } public DraggableDot(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(true); setClickable(true); mLegend = ""; mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(6); mPaint.setColor(0xFFD00000); mLegendPaint = new TextPaint(); mLegendPaint.setAntiAlias(true); mLegendPaint.setTextAlign(Paint.Align.CENTER); mLegendPaint.setColor(0xFFF0F0FF); mGlow = new Paint(); mGlow.setAntiAlias(true); mGlow.setStrokeWidth(1); mGlow.setStyle(Paint.Style.STROKE); // look up any layout-defined attributes TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DraggableDot); final int N = a.getIndexCount(); for (int i = 0; i < N; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.DraggableDot_radius: { mRadius = a.getDimensionPixelSize(attr, 0); } break; case R.styleable.DraggableDot_legend: { mLegend = a.getText(attr); } break; case R.styleable.DraggableDot_anr: { mAnrType = a.getInt(attr, 0); } break; } } Log.i(TAG, "DraggableDot @ " + this + " : radius=" + mRadius + " legend='" + mLegend + "' anr=" + mAnrType); setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { ClipData data = ClipData.newPlainText("dot", "Dot : " + v.toString()); v.startDrag(data, new ANRShadowBuilder(v, mAnrType == ANR_SHADOW), (Object)v, 0); return true; } }); } void setReportView(TextView view) { mReportView = view; } @Override protected void onDraw(Canvas canvas) { float wf = getWidth(); float hf = getHeight(); final float cx = wf/2; final float cy = hf/2; wf -= getPaddingLeft() + getPaddingRight(); hf -= getPaddingTop() + getPaddingBottom(); float rad = (wf < hf) ? wf/2 : hf/2; canvas.drawCircle(cx, cy, rad, mPaint); if (mLegend != null && mLegend.length() > 0) { canvas.drawText(mLegend, 0, mLegend.length(), cx, cy + mLegendPaint.getFontSpacing()/2, mLegendPaint); } // if we're in the middle of a drag, light up as a potential target if (mDragInProgress && mAcceptsDrag) { for (int i = NUM_GLOW_STEPS; i > 0; i--) { int color = (mHovering) ? WHITE_STEP : GREEN_STEP; color = i*(color | ALPHA_STEP); mGlow.setColor(color); canvas.drawCircle(cx, cy, rad, mGlow); rad -= 0.5f; canvas.drawCircle(cx, cy, rad, mGlow); rad -= 0.5f; } } } @Override protected void onMeasure(int widthSpec, int heightSpec) { int totalDiameter = 2*mRadius + getPaddingLeft() + getPaddingRight(); setMeasuredDimension(totalDiameter, totalDiameter); } /** * Drag and drop */ @Override public boolean onDragEvent(DragEvent event) { boolean result = false; switch (event.getAction()) { case DragEvent.ACTION_DRAG_STARTED: { // claim to accept any dragged content Log.i(TAG, "Drag started, event=" + event); // cache whether we accept the drag to return for LOCATION events mDragInProgress = true; mAcceptsDrag = result = true; // Redraw in the new visual state if we are a potential drop target if (mAcceptsDrag) { invalidate(); } } break; case DragEvent.ACTION_DRAG_ENDED: { Log.i(TAG, "Drag ended."); if (mAcceptsDrag) { invalidate(); } mDragInProgress = false; mHovering = false; } break; case DragEvent.ACTION_DRAG_LOCATION: { // we returned true to DRAG_STARTED, so return true here Log.i(TAG, "... seeing drag locations ..."); result = mAcceptsDrag; } break; case DragEvent.ACTION_DROP: { Log.i(TAG, "Got a drop! dot=" + this + " event=" + event); if (mAnrType == ANR_DROP) { sleepSixSeconds(); } processDrop(event); result = true; } break; case DragEvent.ACTION_DRAG_ENTERED: { Log.i(TAG, "Entered dot @ " + this); mHovering = true; invalidate(); } break; case DragEvent.ACTION_DRAG_EXITED: { Log.i(TAG, "Exited dot @ " + this); mHovering = false; invalidate(); } break; default: Log.i(TAG, "other drag event: " + event); result = mAcceptsDrag; break; } return result; } private void processDrop(DragEvent event) { final ClipData data = event.getClipData(); final int N = data.getItemCount(); for (int i = 0; i < N; i++) { ClipData.Item item = data.getItemAt(i); Log.i(TAG, "Dropped item " + i + " : " + item); if (mReportView != null) { String text = item.coerceToText(getContext()).toString(); if (event.getLocalState() == (Object) this) { text += " : Dropped on self!"; } mReportView.setText(text); } } } } public class Test extends Activity { TextView mResultText; DraggableDot mHiddenDot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView text = (TextView) findViewById(R.id.drag_text); DraggableDot dot = (DraggableDot) findViewById(R.id.drag_dot_1); dot.setReportView(text); dot = (DraggableDot) findViewById(R.id.drag_dot_2); dot.setReportView(text); dot = (DraggableDot) findViewById(R.id.drag_dot_3); dot.setReportView(text); mHiddenDot = (DraggableDot) findViewById(R.id.drag_dot_hidden); mHiddenDot.setReportView(text); mResultText = (TextView) findViewById(R.id.drag_result_text); mResultText.setOnDragListener(new View.OnDragListener() { public boolean onDrag(View v, DragEvent event) { final int action = event.getAction(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: { // Bring up a fourth draggable dot on the fly. Note that it // is properly notified about the ongoing drag, and lights up // to indicate that it can handle the current content. mHiddenDot.setVisibility(View.VISIBLE); } break; case DragEvent.ACTION_DRAG_ENDED: { // Hide the surprise again mHiddenDot.setVisibility(View.INVISIBLE); // Report the drop/no-drop result to the user final boolean dropped = event.getResult(); mResultText.setText(dropped ? "Dropped!" : "No drop"); } break; } return false; } }); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- Layout description of the DragAndDrop sample's main activity --> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dot="http://schemas.android.com/apk/res/com.example.android.apis" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/drag_explanation" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="drag_explanation" /> <app.test.DraggableDot android:id="@+id/drag_dot_1" android:layout_width="wrap_content" android:layout_height="wrap_content" dot:radius="64dp" android:padding="15dp" android:layout_below="@id/drag_explanation" /> <app.test.DraggableDot android:id="@+id/drag_dot_2" android:layout_width="wrap_content" android:layout_height="wrap_content" dot:radius="64dp" android:padding="15dp" android:layout_below="@id/drag_explanation" android:layout_toRightOf="@id/drag_dot_1" dot:legend="Drag ANR" dot:anr="thumbnail" /> <app.test.DraggableDot android:id="@+id/drag_dot_3" android:layout_width="wrap_content" android:layout_height="wrap_content" dot:radius="64dp" android:padding="15dp" android:layout_below="@id/drag_dot_1" android:layout_alignLeft="@id/drag_dot_1" dot:legend="Drop ANR" dot:anr="drop" /> <app.test.DraggableDot android:id="@+id/drag_dot_hidden" android:layout_width="wrap_content" android:layout_height="wrap_content" dot:radius="64dp" android:padding="15dp" android:layout_toRightOf="@id/drag_dot_3" android:layout_alignTop="@id/drag_dot_3" android:visibility="invisible" dot:legend="Surprise!" /> <TextView android:id="@+id/drag_result_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/drag_explanation" android:layout_alignRight="@id/drag_explanation" android:layout_toRightOf="@id/drag_dot_2" /> <TextView android:id="@+id/drag_text" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:layout_below="@id/drag_dot_3" android:layout_alignLeft="@id/drag_dot_3" /> </RelativeLayout>
Drag and drop
package app.test; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.Fragment; import android.content.ClipData; 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.util.Log; import android.view.DragEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.CycleInterpolator; import android.widget.TextView; class Dot extends View implements View.OnDragListener { private static final int DEFAULT_RADIUS = 50; private static final int DEFAULT_COLOR = Color.WHITE; private static final int SELECTED_COLOR = Color.MAGENTA; protected static final String DOTTAG = "DragDot"; private Paint mNormalPaint; private Paint mDraggingPaint; private int mColor = DEFAULT_COLOR; private int mRadius = DEFAULT_RADIUS; private boolean inDrag; public Dot(Context context, AttributeSet attrs) { super(context, attrs); mNormalPaint = new Paint(); mNormalPaint.setColor(mColor); mNormalPaint.setAntiAlias(true); mDraggingPaint = new Paint(); mDraggingPaint.setColor(SELECTED_COLOR); mDraggingPaint.setAntiAlias(true); setOnLongClickListener(lcListener); setOnDragListener(this); } private static View.OnLongClickListener lcListener = new View.OnLongClickListener() { private boolean mDragInProgress; public boolean onLongClick(View v) { ClipData data = ClipData.newPlainText("DragData", (String) v.getTag()); mDragInProgress = v.startDrag(data, new View.DragShadowBuilder(v), (Object) v, 0); Log.v((String) v.getTag(), "starting drag? " + mDragInProgress); return true; } }; @Override protected void onMeasure(int widthSpec, int heightSpec) { int size = 2 * mRadius + getPaddingLeft() + getPaddingRight(); setMeasuredDimension(size, size); } public boolean onDrag(View v, DragEvent event) { String dotTAG = (String) getTag(); if (event.getLocalState() != this) { return false; } boolean result = true; int action = event.getAction(); float x = event.getX(); float y = event.getY(); switch (action) { case DragEvent.ACTION_DRAG_STARTED: inDrag = true; break; case DragEvent.ACTION_DRAG_LOCATION: break; case DragEvent.ACTION_DRAG_ENTERED: break; case DragEvent.ACTION_DRAG_EXITED: break; case DragEvent.ACTION_DROP: result = false; break; case DragEvent.ACTION_DRAG_ENDED: inDrag = false; // change color of original dot back break; default: result = false; break; } return result; } public void draw(Canvas canvas) { float cx = this.getWidth() / 2 + getLeftPaddingOffset(); float cy = this.getHeight() / 2 + getTopPaddingOffset(); Paint paint = mNormalPaint; if (inDrag) paint = mDraggingPaint; canvas.drawCircle(cx, cy, mRadius, paint); invalidate(); } } class DropZone extends Fragment { private View dropTarget; private TextView dropMessage; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle) { View v = inflater.inflate(R.layout.row, container, false); dropMessage = (TextView) v.findViewById(R.id.dropmessage); dropTarget = (View) v.findViewById(R.id.droptarget); dropTarget.setOnDragListener(new View.OnDragListener() { private static final String DROPTAG = "DropTarget"; private int dropCount = 0; private ObjectAnimator anim; public boolean onDrag(View v, DragEvent event) { int action = event.getAction(); boolean result = true; switch (action) { case DragEvent.ACTION_DRAG_STARTED: break; case DragEvent.ACTION_DRAG_ENTERED: anim = ObjectAnimator .ofFloat((Object) v, "alpha", 1f, 0.5f); anim.setInterpolator(new CycleInterpolator(40)); anim.setDuration(30 * 1000); anim.start(); break; case DragEvent.ACTION_DRAG_EXITED: if (anim != null) { anim.end(); anim = null; } break; case DragEvent.ACTION_DRAG_LOCATION: Log.v(DROPTAG, "drag proceeding in dropTarget: " + event.getX() + ", " + event.getY()); break; case DragEvent.ACTION_DROP: Log.v(DROPTAG, "drag drop in dropTarget"); if (anim != null) { anim.end(); anim = null; } ClipData data = event.getClipData(); Log.v(DROPTAG, "Item data is " + data.getItemAt(0).getText()); dropCount++; String message = dropCount + " drop"; if (dropCount > 1) message += "s"; dropMessage.setText(message); break; case DragEvent.ACTION_DRAG_ENDED: Log.v(DROPTAG, "drag ended in dropTarget"); if (anim != null) { anim.end(); anim = null; } break; default: Log.v(DROPTAG, "other action in dropzone: " + action); result = false; } return result; } }); return v; } } class Palette extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle) { View v = inflater.inflate(R.layout.add_edit, container, false); return v; } } public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //layout/main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is res/layout/main.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class="app.test.TitlesFragment" android:id="@+id/titles" android:layout_width="match_parent" android:layout_height="match_parent" /> android:background="#00550033" /> <FrameLayout android:id="@+id/details" android:layout_weight="2" android:layout_width="0px" android:layout_height="match_parent" /> </LinearLayout> //row.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="horizontal" > <View android:id="@+id/droptarget" android:layout_width="75dp" android:layout_height="75dp" android:layout_gravity="center_vertical" android:background="#00ff00" /> <TextView android:id="@+id/dropmessage" android:text="0 drops" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:paddingLeft="50dp" android:textSize="17sp" /> </LinearLayout> //add_edit.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is res/layout/palette.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dot="http://schemas.android.com/apk/res/app.test.demo" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <app.test.Dot android:id="@+id/dot1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="30dp" android:tag="Blue dot" dot:color="#ff1111ff" dot:radius="20dp" /> <app.test.Dot android:id="@+id/dot2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:tag="White dot" dot:color="#ffffffff" dot:radius="40dp" /> </LinearLayout>
Drag and move a dot
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.os.Bundle; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; class Dot extends View { private static final float RADIUS = 20; private float x = 30; private float y = 30; private float initialX; private float initialY; private float offsetX; private float offsetY; private Paint myPaint; private Paint backgroundPaint; public Dot(Context context, AttributeSet attrs) { super(context, attrs); backgroundPaint = new Paint(); backgroundPaint.setColor(Color.BLUE); myPaint = new Paint(); myPaint.setColor(Color.WHITE); myPaint.setAntiAlias(true); } public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: initialX = x; initialY = y; offsetX = event.getX(); offsetY = event.getY(); break; case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: x = initialX + event.getX() - offsetX; y = initialY + event.getY() - offsetY; break; } return (true); } public void draw(Canvas canvas) { int width = canvas.getWidth(); int height = canvas.getHeight(); canvas.drawRect(0, 0, width, height, backgroundPaint); canvas.drawCircle(x, y, RADIUS, myPaint); invalidate(); } } public class Test extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is res/layout/main.xml --> <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.Dot android:id="@+id/dot" android:tag="trueDot" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Using DatePickerDialog
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>
Set initial value for DatePicker
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("CheckBoxActivity"); setContentView(R.layout.main); DatePicker dp = (DatePicker)this.findViewById(R.id.date_picker); dp.init(2011, 7, 17, 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="wrap_content"> <DatePicker android:id="@+id/date_picker" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Using DatePicker
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>
16-Chronometer
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.os.SystemClock; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Chronometer; public class ChronometerDemo extends Activity { Chronometer mChronometer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button; mChronometer = (Chronometer) findViewById(R.id.chronometer); // Watch for button clicks. button = (Button) findViewById(R.id.start); button.setOnClickListener(mStartListener); button = (Button) findViewById(R.id.stop); button.setOnClickListener(mStopListener); button = (Button) findViewById(R.id.reset); button.setOnClickListener(mResetListener); button = (Button) findViewById(R.id.set_format); button.setOnClickListener(mSetFormatListener); button = (Button) findViewById(R.id.clear_format); button.setOnClickListener(mClearFormatListener); } View.OnClickListener mStartListener = new OnClickListener() { public void onClick(View v) { mChronometer.start(); } }; View.OnClickListener mStopListener = new OnClickListener() { public void onClick(View v) { mChronometer.stop(); } }; View.OnClickListener mResetListener = new OnClickListener() { public void onClick(View v) { mChronometer.setBase(SystemClock.elapsedRealtime()); } }; View.OnClickListener mSetFormatListener = new OnClickListener() { public void onClick(View v) { mChronometer.setFormat("Formatted time (%s)"); } }; View.OnClickListener mClearFormatListener = new OnClickListener() { public void onClick(View v) { mChronometer.setFormat(null); } }; } //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="vertical" android:padding="4dip" android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <Chronometer android:id="@+id/chronometer" android:format="chronometer_initial_format" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0" android:paddingBottom="30dip" android:paddingTop="30dip" /> <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="chronometer_start"> <requestFocus /> </Button> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="chronometer_stop"> </Button> <Button android:id="@+id/reset" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="chronometer_reset"> </Button> <Button android:id="@+id/set_format" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="chronometer_set_format"> </Button> <Button android:id="@+id/clear_format" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="chronometer_clear_format"> </Button> </LinearLayout>
17-BackupHelper
package com.sputnik.wispr.util; import java.io.IOException; import android.app.backup.BackupAgentHelper; import android.app.backup.BackupDataInput; import android.app.backup.BackupDataOutput; import android.app.backup.SharedPreferencesBackupHelper; import android.content.Context; import android.os.ParcelFileDescriptor; import android.util.Log; public class BackupAgentHelperWrapper extends BackupAgentHelper { private static String TAG = BackupAgentHelperWrapper.class.getName(); private BackupAgentHelper instance = null; private static boolean checkAvailability = true; private static boolean isAvailable = false; /** * Class initialization which will fail when the helper class doesn't exist */ static { if (checkAvailability) { try { Class.forName("android.app.backup.BackupAgentHelper"); isAvailable = true; } catch (Exception e) { isAvailable = false; } finally { checkAvailability = false; } Log.d(TAG, "isAvailable:" + isAvailable); } } public BackupAgentHelperWrapper() { if (isAvailable) { instance = new BackupAgentHelper(); Log.d(TAG, "instance:" + instance); } } protected Context getBackupAgentInstance() { Context ctx = null; if (isAvailable) { ctx = instance; } return ctx; } @Override public void onCreate() { if (isAvailable) { instance.onCreate(); } } @Override public void onDestroy() { if (isAvailable) { instance.onDestroy(); } } @Override public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) throws IOException { if (isAvailable) { instance.onBackup(oldState, data, newState); } } @Override public void onRestore(BackupDataInput data, int appVersionCode, ParcelFileDescriptor newState) throws IOException { if (isAvailable) { instance.onRestore(data, appVersionCode, newState); } } public void addHelper(String keyPrefix, SharedPreferencesBackupHelper helper) { if (isAvailable) { instance.addHelper(keyPrefix, helper); } } @Override public String getPackageName() { String pkgName = null; if (isAvailable) { Log.d(TAG, "getPackageName@instance:" + instance); pkgName = instance.getPackageName(); } return pkgName; } }
18-AlertDialog
show Yes No Prompt
import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.ActivityManager.MemoryInfo; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.net.Uri; import android.text.Html; class Utils { public static void showYesNoPrompt(Context _context, String title, String message, OnClickListener onYesListener, OnClickListener onNoListener) { AlertDialog.Builder builder = new AlertDialog.Builder(_context); builder.setTitle(title); builder.setIcon(android.R.drawable.ic_dialog_info); // lame icon builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton("Yes", onYesListener); builder.setNegativeButton("No", onNoListener); builder.show(); } }
Helper Alert
import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import android.app.AlertDialog; class Tools { /** * Helper Alert * @param title * @param message */ public static void AlertDialog(final Context ctx, final CharSequence title, final CharSequence message) { new AlertDialog.Builder(ctx) // .setIcon(R.drawable.icon) .setTitle(title) .setMessage(message) .setPositiveButton("Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .show(); } }
show Alert
import android.app.AlertDialog.Builder; import android.content.Context; class Util { public static void showAlert(Context context, String title, String text, boolean showOk) { Builder alertBuilder = new Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(text); if (showOk) alertBuilder.setNeutralButton("??", null); alertBuilder.create().show(); } public static void showAlert(Context context, String title, String text) { showAlert(context, title, text, true); } }
show Message
import android.app.Activity; import android.app.ActivityManager; import android.app.AlertDialog; import android.app.ActivityManager.MemoryInfo; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.net.Uri; import android.text.Html; class Utils { public static void showMessage(Context _context, String title, String message, int icon, DialogInterface.OnClickListener ackHandler) { AlertDialog.Builder builder = new AlertDialog.Builder(_context); builder.setTitle(title); builder.setMessage(Html.fromHtml(message)); builder.setCancelable(false); builder.setPositiveButton("Acknowledged", ackHandler); builder.setIcon(icon); builder.show(); } }
open First Time Popup
import android.app.AlertDialog; import android.content.Context; class UIHelper { public static void openFirstTimePopup(final Context context) { final String html = "Thank you!"; final AlertDialog.Builder builder = new AlertDialog.Builder(context). setCancelable(true). setTitle("Welcome!"). setMessage(html). setNegativeButton("Close",null); final AlertDialog di = builder.create(); di.show(); } }
19-CheckBox
package app.test; import android.app.Activity; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; public class Test extends Activity implements CompoundButton.OnCheckedChangeListener { CheckBox cb; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); cb = (CheckBox) findViewById(R.id.check); cb.setOnCheckedChangeListener(this); } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { cb.setText("This checkbox is: checked"); } else { cb.setText("This checkbox is: unchecked"); } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This checkbox is: unchecked" />
Use choice mode on a list. This list is in CHOICE_MODE_MULTIPLE mode, which means the items behave like checkboxes.
package com.example.android.apis.view; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class List11 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; }
Use choice mode on a list. This list is in CHOICE_MODE_SINGLE mode, which means the items behave like checkboxes.
package com.example.android.apis.view; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class List10 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; }
flips the checkbox to unchecked if it was checked
package app.test; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CheckBox fishCB = (CheckBox) findViewById(R.id.fishCB); if (fishCB.isChecked()) fishCB.toggle(); fishCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton arg0, boolean isChecked) { Log.v("CheckBoxActivity", (isChecked ? "checked" : "not checked")); } }); } public void doClick(View view) { Log.v("CheckBoxActivity", ((CheckBox) view).isChecked() ? "checked" : "not checked"); } } //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"> <CheckBox android:id="@+id/chickenCB" android:text="Chicken" android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/fishCB" android:text="Fish" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/steakCB" android:text="Steak" android:checked="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="doClick" /> </LinearLayout>
Get CheckBox value
package app.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; 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("CheckBoxActivity"); setContentView(R.layout.main); find_and_modify_text_view(); } private void find_and_modify_text_view() { plain_cb = (CheckBox) findViewById(R.id.plain_cb); serif_cb = (CheckBox) findViewById(R.id.serif_cb); italic_cb = (CheckBox) findViewById(R.id.italic_cb); bold_cb = (CheckBox) findViewById(R.id.bold_cb); Button get_view_button = (Button) findViewById(R.id.get_view_button); get_view_button.setOnClickListener(get_view_button_listener); } private Button.OnClickListener get_view_button_listener = new Button.OnClickListener() { public void onClick(View v) { String r = ""; if (plain_cb.isChecked()) { r = r + "," + plain_cb.getText(); } if (serif_cb.isChecked()) { r = r + "," + serif_cb.getText(); } if (italic_cb.isChecked()) { r = r + "," + italic_cb.getText(); } if (bold_cb.isChecked()) { r = r + "," + bold_cb.getText(); } setTitle("Checked: " + r); } }; } //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" > <CheckBox android:id="@+id/plain_cb" android:text="Plain" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/serif_cb" android:text="Serif" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" /> <CheckBox android:id="@+id/bold_cb" android:text="Bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" /> <CheckBox android:id ="@+id/italic_cb" android:text="Italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic" /> <Button android:id="@+id/get_view_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get CheckBox" /> </LinearLayout>
Is CheckBox selected
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>
20-GridView
Using GridView
package com.commonsware.android.grid; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.TextView; public class GridDemo 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); GridView g=(GridView) findViewById(R.id.grid); g.setAdapter(new FunnyLookingAdapter(this, android.R.layout.simple_list_item_1, items)); g.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { selection.setText(items[position]); } public void onNothingSelected(AdapterView<?> parent) { selection.setText(""); } private class FunnyLookingAdapter extends ArrayAdapter { Context ctxt; FunnyLookingAdapter(Context ctxt, int resource, String[] items) { super(ctxt, resource, items); this.ctxt=ctxt; } public View getView(int position, View convertView, ViewGroup parent) { TextView label=(TextView)convertView; if (convertView==null) { convertView=new TextView(ctxt); label=(TextView)convertView; } label.setText(items[position]); return(convertView); } } } //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" /> <GridView android:id="@+id/grid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:verticalSpacing="35px" android:horizontalSpacing="5px" android:numColumns="auto_fit" android:columnWidth="100px" android:stretchMode="columnWidth" android:gravity="center" /> </LinearLayout>
This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL, a.k.a. selection mode on GridView.
package com.example.android.apis.view; import com.example.android.apis.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Checkable; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.ImageView; import java.util.List; /** * This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL, a.k.a. selection mode on GridView. */ public class Grid3 extends Activity { GridView mGrid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadApps(); setContentView(R.layout.grid_1); mGrid = (GridView) findViewById(R.id.myGrid); mGrid.setAdapter(new AppsAdapter()); mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL); mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener()); } private List<ResolveInfo> mApps; private void loadApps() { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mApps = getPackageManager().queryIntentActivities(mainIntent, 0); } public class AppsAdapter extends BaseAdapter { public AppsAdapter() { } public View getView(int position, View convertView, ViewGroup parent) { CheckableLayout l; ImageView i; if (convertView == null) { i = new ImageView(Grid3.this); i.setScaleType(ImageView.ScaleType.FIT_CENTER); i.setLayoutParams(new ViewGroup.LayoutParams(50, 50)); l = new CheckableLayout(Grid3.this); l.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT, GridView.LayoutParams.WRAP_CONTENT)); l.addView(i); } else { l = (CheckableLayout) convertView; i = (ImageView) l.getChildAt(0); } ResolveInfo info = mApps.get(position); i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager())); return l; } public final int getCount() { return mApps.size(); } public final Object getItem(int position) { return mApps.get(position); } public final long getItemId(int position) { return position; } } public class CheckableLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableLayout(Context context) { super(context); } public void setChecked(boolean checked) { mChecked = checked; setBackgroundDrawable(checked ? getResources().getDrawable(R.drawable.blue) : null); } public boolean isChecked() { return mChecked; } public void toggle() { setChecked(!mChecked); } } public class MultiChoiceModeListener implements GridView.MultiChoiceModeListener { public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.setTitle("Select Items"); mode.setSubtitle("One item selected"); return true; } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return true; } public void onDestroyActionMode(ActionMode mode) { } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { int selectCount = mGrid.getCheckedItemCount(); switch (selectCount) { case 1: mode.setSubtitle("One item selected"); break; default: mode.setSubtitle("" + selectCount + " items selected"); break; } } } } //grid_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. --> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myGrid" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:numColumns="auto_fit" android:columnWidth="60dp" android:stretchMode="columnWidth" android:gravity="center" />
GridView layout
package com.example.android.apis.view; import android.app.Activity; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import java.util.List; //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; public class Grid1 extends Activity { GridView mGrid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); loadApps(); // do this in onresume? setContentView(R.layout.grid_1); mGrid = (GridView) findViewById(R.id.myGrid); mGrid.setAdapter(new AppsAdapter()); } private List<ResolveInfo> mApps; private void loadApps() { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); mApps = getPackageManager().queryIntentActivities(mainIntent, 0); } public class AppsAdapter extends BaseAdapter { public AppsAdapter() { } public View getView(int position, View convertView, ViewGroup parent) { ImageView i; if (convertView == null) { i = new ImageView(Grid1.this); i.setScaleType(ImageView.ScaleType.FIT_CENTER); i.setLayoutParams(new GridView.LayoutParams(50, 50)); } else { i = (ImageView) convertView; } ResolveInfo info = mApps.get(position); i.setImageDrawable(info.activityInfo.loadIcon(getPackageManager())); return i; } public final int getCount() { return mApps.size(); } public final Object getItem(int position) { return mApps.get(position); } public final long getItemId(int position) { return position; } } } //grid_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. --> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myGrid" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:numColumns="auto_fit" android:columnWidth="60dp" android:stretchMode="columnWidth" android:gravity="center" />
Using GridView to display Contact people
package app.test; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.provider.Contacts.People; import android.widget.GridView; import android.widget.SimpleCursorAdapter; public class Test extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gv = (GridView)findViewById(R.id.gridview); Cursor c = managedQuery(People.CONTENT_URI, null, null, null, People.NAME); String[] cols = new String[]{People.NAME}; int[] views = new int[] {android.R.id.text1}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, cols, views); gv.setAdapter(adapter); } } //main.xml <?xml version="1.0" encoding="utf-8"?> <!-- This file is at /res/layout/gridview.xml --> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10px" android:verticalSpacing="10px" android:horizontalSpacing="10px" android:numColumns="auto_fit" android:columnWidth="100px" android:stretchMode="columnWidth" android:gravity="center" />
Using GridView to show images
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.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class Test extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setTitle("GridViewActivity"); GridView gridview = (GridView) findViewById(R.id.grid_view); gridview.setAdapter(new ImageAdapter(this)); } public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } private Integer[] mThumbIds = { R.drawable.icon, R.drawable.icon, }; } } //main.xml <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/grid_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:columnWidth="90dp" android:stretchMode="columnWidth" android:gravity="center" />
Using GridView to display images
package app.test; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; public class Test extends Activity { Integer[] imageIDs = { R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon, R.drawable.icon }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(new ImageAdapter(this)); gridView.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(); } }); } public class ImageAdapter extends BaseAdapter { private Context context; public ImageAdapter(Context c) { context = c; } //---returns the number of images--- public int getCount() { return imageIDs.length; } //---returns the ID of an item--- public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } //---returns an ImageView view--- public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(context); imageView.setLayoutParams(new GridView.LayoutParams(185, 185)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(5, 5, 5, 5); } else { imageView = (ImageView) convertView; } imageView.setImageResource(imageIDs[position]); return imageView; } } } //main.xml <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:columnWidth="90dp" android:stretchMode="columnWidth" android:gravity="center" />