86
Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Android Adapters, An Introduction

Embed Size (px)

Citation preview

Page 1: Android Adapters, An Introduction

Android Application Development Training Tutorial

For more info visit

http://www.zybotech.in

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 2: Android Adapters, An Introduction

Android Adapters: an introduction

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

An AdapterView is a view whose children are determined by an Adapter.

Some examples of AdapterViews are ListView, GridView, Spinner and Gallery.

There are several types or sub-classes of Adapter:

ListAdapter: Extended Adapter that is the bridge between a ListView and the data that backs the

list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.

Introduction

In most mobile applications, we find a frequent usage of lists. A list is not often as simple as an array of strings, of integer... Furthermore, the data could be taken or stored in a remote machine. In any case, we’ll be taking a look at what it takes to begin with a simple ListActivity.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 3: Android Adapters, An Introduction

The HowTo

First of all, if you've already taken a look at the first tutorial "HelloWorld", you might know how to create a new Android project on eclipse. So, to begin, you have to create a new Android Project (1.1 or newer) and name the activity MyListActivity (or whatever you prefer.).Next, modify your activity "MyListActivity" to extend the Android class ListActivity and adjust your code to look like the following:

package com.wikinut.android;

import android.app.ListActivity;import android.os.Bundle;import android.widget.ListAdapter;

public class MainListView extends ListActivity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle icicle) {super.onCreate(icicle);

ListAdapter adapter = createAdapter();setListAdapter(adapter);}

/*** Creates and returns a list adapter for the current list activity* @return*/protected ListAdapter createAdapter(){return null;}}

Sounds good, isn't it?. We have a method to create our list adapter. Let’s see then what we mean by adapters.

Adapters group a collection of objects to an activity. In our case, we will create a simple list of strings (which in fact, is already provided by Android: ArrayAdapter)

Bring some chages on your createAdapter() method to be like this:

/*** Creates and returns a list adapter for the current list activity* @return*/protected ListAdapter createAdapter(){// Create some mock dataString[] testValues = new String[] {"Test1","Test2","Test3"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 4: Android Adapters, An Introduction

};

// Create a simple array adapter (of type string) with the test valuesListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, testValues);

return adapter;}

The Context is simply the source of data in the list. In our application it’s simple, but sometimes it can be harder and more complex.The Layout is where the data will be rendered (and how it will look.) We’re using a built-in Android layout for our needs (simple_list_item_1).The Data is what will be rendered, and is a simple list of strings.

Final code should be like this:

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 5: Android Adapters, An Introduction

package com.wikinut.android;

import android.app.ListActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListAdapter;

public class MainListView extends ListActivity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle icicle) {super.onCreate(icicle);

ListAdapter adapter = createAdapter();setListAdapter(adapter);}

/*** Creates and returns a list adapter for the current list activity* @return*/protected ListAdapter createAdapter(){// Create some mock dataString[] testValues = new String[] {"Test1","Test2","Test3"};

// Create a simple array adapter (of type string) with the test valuesListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, testValues);

return adapter;}}

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 6: Android Adapters, An Introduction

Customize Android ListView via ListAdapter

In this tutorial I will discuss how to create Listview that can be customized with one icons and two text fields via a ListAdapter that is customized just for that particular view.

This post might be a bit longer than usual but should be worth the 10 minutes copy and paste and testing. I modify this example from live code, removing all the sensitive information. let me know if you need more clarification.

0. Create new android project as usual. You can use Android HelloWorld Tutorial as the pointer.

1. Create a bean for object that will populate the field. In this case we create a bean to hold information about options available to create a ‘test’. Basically it is a class containing variable for two strings. You can put this directly in your SRC folder… say CreateTestOption.java

01 public class CreateTestOption{

02     private String name;

03     private String description;

04     public String getName() {

05         return name;

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 7: Android Adapters, An Introduction

06     }

07     public void setName(String name) {

08         this.name = name;

09     }

10     public String getDescription() {

11         return description;

12     }

13     public void setDescription(String description) {

14         this.description = description;

15     }

16 }

2. Create the layout for the activity that display the list. This will be the layout for displaying the activity class. You can put this in res/layout folder

01 <?xml version="1.0" encoding="utf-8"?>

02 <LinearLayout

03     xmlns:android="http://schemas.android.com/apk/res/android"

04     android:id="@+id/main"

05     android:orientation="vertical"

06     android:layout_width="fill_parent"

07     android:layout_height="fill_parent"

08     android:background="@color/white"

09     >

10     <LinearLayout

11         android:layout_width="fill_parent"

12         android:layout_height="wrap_content"

13         android:background="@color/dark_blue"

14         >

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 8: Android Adapters, An Introduction

15         <TextView

16            android:id="@+id/list_header_title"

17            android:text="@string/create_test_activity_title"

18            style="@style/listSeparatorTextViewStyle" />

19     </LinearLayout>

20     <ListView

21         android:id="@android:id/list"

22         android:layout_height="0dip"

23         android:layout_width="fill_parent"

24         android:layout_weight="1"

25         android:scrollbars="vertical"

26         android:footerDividersEnabled="true"

27         style="@style/listViewStyle"/>

28 </LinearLayout>

3. And if you notice, for easier management of more complex project, I define the style and color in separate files namely styles.xml and colors.xml in RES/VALUES folder where original strings.xml is located

styles.xml

01 <?xml version="1.0" encoding="UTF-8"?>

02     <!-- Styling file -->

03 <resources>

04    <style name="listSeparatorTextViewStyle" parent="@android:attr/listSeparatorTextViewStyle">

05         <item name="android:layout_height">wrap_content</item>

06         <item name="android:layout_width">fill_parent</item>

07         <item name="android:textSize">15dip</item>

08         <item name="android:paddingTop">2dip</item>

09         <item name="android:paddingBottom">3dip</item>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 9: Android Adapters, An Introduction

10         <item name="android:paddingLeft">5dip</item>

11         <item name="android:paddingRight">10dip</item>

12         <item name="android:textAppearance">@android:style/TextAppearance.Small</item>

13         <item name="android:shadowColor">#111111</item>

14         <item name="android:shadowRadius">1</item>

15         <item name="android:shadowDy">1</item>

16         <item name="android:textStyle">bold</item>

17         <item name="android:textColor">@android:color/white</item>

18         <item name="android:background">@color/dark_blue</item>

19     </style>

20     <style name="listViewStyle" parent="@android:attr/listViewStyle">

21         <item name="android:textColor">@android:color/black</item>

22         <item name="android:background">@color/white</item>

23     </style>

24     <style name="genericListItemFirstTextView">

25         <item name="android:textSize">15dip</item>

26         <item name="android:textStyle">bold</item>

27         <item name="android:textColor">@color/black</item>

28     </style>

29     <style name="genericListItemSecondTextView">

30         <item name="android:textSize">13dip</item>

31         <item name="android:textColor">@color/grey/item>

32     </style>

33     <style name="genericListItemShoutTextView">

34         <item name="android:textSize">13dip</item>

35         <item name="android:textColor">@color/grey</item>

36     </style>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 10: Android Adapters, An Introduction

37 </resources>

colors.xml

01 <?xml version="1.0" encoding="utf-8"?>

02 <resources>

03     <color name="white">#fff</color>

04     <color name="black">#000</color>

05     <color name="red">#c6360a</color>

06     <color name="green">#688f2b</color>

07     <color name="orange">#f48905</color>

08     <color name="dark_blue">#003366</color>

09         <color name="grey">#888888</color>

10 </resources>

strings.xml

01 <?xml version="1.0" encoding="utf-8"?>

02     <!-- all the strings required for the app arranged alphabetically-->

03 <resources>

04         <!-- A -->

05         <string name="app_name">dummy test</string>

06         <!-- B -->

07         <!-- C -->

08         <string name="create_test_activity_title">Choose your next test</string>

09         <string name="create_test_activity_help_button">Help</string>

10         <string name="customize_test_type_prompt">Set Exam Type</string>

11         <string name="customize_test_time_prompt">Set Question Type</string>

12 </resources>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 11: Android Adapters, An Introduction

4. Create the layout for the individual item in the list. Name it generic_list_item.xml and put it inside res/layout folder.

01 <?xml version="1.0" encoding="utf-8"?>

02 <LinearLayout

03   xmlns:android="http://schemas.android.com/apk/res/android"

04   android:layout_width="fill_parent"

05   android:layout_height="wrap_content"

06   android:paddingLeft="8dip"

07   android:paddingRight="8dip"

08   android:paddingTop="5dip"

09   android:paddingBottom="8dip"

10   android:orientation="horizontal"

11   >

12   <ImageView

13     android:id="@+id/left_icon"

14     android:layout_width="32dip"

15     android:layout_height="32dip"

16     android:src="@drawable/any_32_32_icon_in_png"

17     android:scaleType="fitCenter"

18     android:gravity="center_horizontal"

19     android:layout_marginTop="3dip" />

20   <LinearLayout

21     android:layout_width="fill_parent"

22     android:layout_height="wrap_content"

23     android:orientation="vertical"

24     android:paddingLeft="8dip" >

25     <TextView

26       android:id="@+id/firstLineTextView"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 12: Android Adapters, An Introduction

27       android:layout_width="fill_parent"

28       android:layout_height="wrap_content"

29       android:paddingBottom="2dip"

30       android:textAppearance="@style/genericListItemFirstTextView"

31       android:singleLine="true"

32       android:ellipsize="marquee"/>

33     <ProgressBar android:id="@+id/progress_horizontal"

34       style="?android:attr/progressBarStyleHorizontal"

35       android:layout_width="fill_parent"

36       android:layout_height="wrap_content"

37       android:max="100"

38       android:progress="50"

39       android:visibility="gone"

40       />

41     <TextView

42       android:id="@+id/secondLineTextView"

43       android:layout_width="wrap_content"

44       android:layout_height="wrap_content"

45       android:maxLines="1"

46       android:scrollHorizontally="true"

47       android:ellipsize="marquee"

48       android:textAppearance="@style/genericListItemSecondTextView" />

49   </LinearLayout>

50 </LinearLayout>

5. create adapter class that will populate listview with custom data

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 13: Android Adapters, An Introduction

01 public class CreateTestAdapter extends ArrayAdapter<CreateTestOption> {

02     public static final String TAG = CreateTestAdapter.class.getSimpleName();

03     public static final boolean DEBUG = true;

04     private ArrayList<CreateTestOption> tests;

05     private LayoutInflater mInflater;

06     private int layoutResource;

07     public CreateTestAdapter(Context context, int textViewResourceId,

08             ArrayList<ViewCreateTestActivity.CreateTestOption> mOptions) {

09         super(context, textViewResourceId, mOptions);

10         if (DEBUG) Log.d(TAG, "create UserTestCategoryAdapter(xxx) ");

11         this.tests = mOptions;

12         if (DEBUG) Log.d(TAG, "set up LayoutInflater from context");

13         this.mInflater = LayoutInflater.from(context);

14         this.layoutResource = textViewResourceId;

15     }

16     @Override

17     public View getView(int position, View convertView, ViewGroup parent) {

18         if (DEBUG) Log.d(TAG, "start getView()");

19         final ViewHolder holder;

20         View v = convertView;

21         if (v == null) {

22             if (DEBUG) Log.d(TAG, "mInflater inflate history_list_item");

23             v = mInflater.inflate(layoutResource, null);

24             if (DEBUG) Log.d(TAG, "set up viewHolder");

25             holder = new ViewHolder();

26             holder.icon = (ImageView) v.findViewById(R.id.left_icon);

27             holder.firstLine = (TextView) v.findViewById(R.id.firstLineTextView);

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 14: Android Adapters, An Introduction

28             holder.timeTextView = (TextView) v.findViewById(R.id.secondLineTextView);

29             if (DEBUG) Log.d(TAG, "attach viewHolder to convertview");

30             v.setTag(holder);

31         }else {

32             // Get the ViewHolder back to get fast access to the TextView

33             // and the ImageView.

34             holder = (ViewHolder) v.getTag();

35         }

36         CreateTestOption c = tests.get(position);

37         if (c != null) {

38             if (DEBUG) Log.d(TAG, "t is not null");

39             //loading first line

40             holder.firstLine.setText(c.getName());

41             holder.firstLine.setVisibility(View.VISIBLE);

42             //loading second line

43             holder.timeTextView.setText(c.getDescription());

44             holder.timeTextView.setVisibility(View.VISIBLE);

45             //loading icon

46             //TODO make mechanism so the icon will appear differently

47             holder.icon.setImageResource(R.drawable.icon_done_32x32);

48         }

49         else {

50             // This is going to be a shout then.

51             if (DEBUG) Log.d(TAG, "t is null");

52             holder.icon.setImageResource(R.drawable.ic_menu_shout);

53             holder.firstLine.setVisibility(View.GONE);

54         }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 15: Android Adapters, An Introduction

55         //TODO create stringformatter

56         if (DEBUG) Log.d(TAG, "return v");

57         return v;

58     }

59     private static class ViewHolder {

60         ImageView icon;

61         TextView firstLine;

62         TextView timeTextView;

63     }

64 }

6. create activity class (at last). for this exercise, just put it in src folder and name it CreateTestActivity.java

This will bind together the layout for activity class,layout for individual list item and adapter for each listitem

01 public class CreateTestActivity extends ListActivity {

02     public static final String TAG = CreateTestActivity.class

03             .getSimpleName();

04     public static final boolean DEBUG = true;

05     private ArrayList<CreateTestOption> m_options = null;

06     private CreateTestAdapter m_adapter;

07     private Runnable createTestActivity;

08     @Override

09     public void onCreate(Bundle savedInstanceState) {

10         super.onCreate(savedInstanceState);

11         setContentView(R.layout.create_test_activity);

12        //ListView list = getListView(); //no need since we use ListActivity instead of activity

13         ensureUi(); //generate the UI and populate its content

14     }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 16: Android Adapters, An Introduction

15     private void getCreateTestOptions() {

16         try {

17             m_options = new ArrayList<CreateTestOption>();

18             //we generate the value here, in reality, you should retrieve

19             //the value from other mechanism such as database or web service

20             CreateTestOption c1 = new CreateTestOption();

21             c1.setName("Quick Start");

22             c1.setDescription("Automatically generate a test in a flash");

23             CreateTestOption c2 = new CreateTestOption();

24             c2.setName("Recommended Package");

25             c2.setDescription("Choose from 3 recommended packages");

26             CreateTestOption c3 = new CreateTestOption();

27             c3.setName("Design Your Own");

28             c3.setDescription("Manually customize your own test");

29             m_options.add(c1);

30             m_options.add(c2);

31             m_options.add(c3);

32             Thread.sleep(15);

33         } catch (Exception e) {

34             if (DEBUG)

35                 Log.d(TAG, "exception exception");

36             Log.e("BACKGROUND_PROC", e.getMessage());

37         }

38         //loading the value together with UI thread

39         //preventing the 'freeze' or some sort

40         runOnUiThread(returnRes);

41         if (DEBUG)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 17: Android Adapters, An Introduction

42             Log.d(TAG, "getTestCategories() ends");

43     }

44     private Runnable returnRes = new Runnable() {

45         @Override

46         public void run() {

47             if (DEBUG) Log.d(TAG, "returnRes runable run() start");

48             if (m_options != null &amp;&amp; m_options.size() > 0) {

49                 if (DEBUG) Log.d(TAG, "m_tests got something");

50                 m_adapter.notifyDataSetChanged();

51                if (DEBUG) Log.d(TAG, "m_adapter.notifydatasetchanged() since m_tests got something");

52                 for (int i = 0; i < m_options.size(); i++)

53                     m_adapter.add(m_options.get(i));

54             }

55             m_adapter.notifyDataSetChanged();

56            if (DEBUG) Log.d(TAG, "m_adapter.notifydatasetchanged() after dismiss m_progressdialog");

57         }

58     };

59     private void ensureUi() {

60         if (DEBUG) Log.d(TAG, "ensureUi() start");

61         if (DEBUG) Log.d(TAG, "create m_options");

62         m_options = new ArrayList<CreateTestOption>();

63         if (DEBUG) Log.d(TAG, "calling CreateTestAdapter()");

64        this.m_adapter = new CreateTestAdapter(this, R.layout.generic_list_item, m_options);

65         if (DEBUG) Log.d(TAG, "listView=getListView()");

66         ListView listView = getListView();

67         if (DEBUG) Log.d(TAG, "lisview setAdapter this.m_adapter");

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 18: Android Adapters, An Introduction

68         listView.setAdapter(this.m_adapter);

69         listView.setSmoothScrollbarEnabled(true);

70         if (DEBUG) Log.d(TAG, "initiate new viewTest = new Runable");

71         createTestActivity = new Runnable() {

72             public void run() {

73                 getCreateTestOptions();

74             }

75         };

76         if (DEBUG) Log.d(TAG, "create new thread with viewTestRunable");

77         Thread thread = new Thread(null, createTestActivity, "MagentoBackground");

78         if (DEBUG) Log.d(TAG, "thread start()");

79         thread.start();

80         listView.setOnItemClickListener(new OnItemClickListener() {

81             @Override

82            public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {

83                 Object obj = (Object)m_adapter.getItem(position);

84                 if (obj != null) {

85                    //TODO set this intent creation based on the unique parameter of the each CreateTestOption class

86                     Intent intent = new Intent();

87                     if (position == 2) {

88                        intent.setClass(ViewCreateTestActivity.this, placeholderActivity2.class);

89                     }else if (position == 1){

90                        intent.setClass(ViewCreateTestActivity.this, placeholderActivity1.class);

91                     }else if (position == 0 ) {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 19: Android Adapters, An Introduction

92                        intent.setClass(ViewCreateTestActivity.this, placeholderActivity0.class);

93                     }

94                     startActivity(intent);

95                 }

96             }

97         });

98     }

99 }

7. Define each placeholderActivityN.class as follows – thanks worked

01 package com.example.helloandroid;

02

03 import android.app.Activity;

04 import android.os.Bundle;

05 import android.widget.TextView;

06

07 public class placeholderActivity1 extends Activity {

08    /** Called when the activity is first created. */

09    @Override

10    public void onCreate(Bundle savedInstanceState) {

11        super.onCreate(savedInstanceState);

12        TextView tv = new TextView(this);

13        tv.setText("This is placeholder class #1");

14        setContentView(tv);

15    }

16 }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 20: Android Adapters, An Introduction

you can do that for the remaining placeholderActivity0 and placeholderActivity2 class. In essence, this will be the target class that you intend to reach upon clicking the list.

8. do not forget to define activity class in in manifest.xml

01 <?xml version="1.0" encoding="utf-8"?>

02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

03     package="com.combankmed.android" android:versionName="2010-08-02"

04     android:versionCode="2010080200">

05     <application

06

07         android:icon="@drawable/icon"

08         android:label="@string/app_name"

09          >

10

11        <activity android:name=".ViewCompleteTestActivity" android:screenOrientation="portrait"></activity>

12        <activity android:name=".ViewCreateTestActivity" android:screenOrientation="portrait">

13 <activity android:name=".placeholderActivity0" android:screenOrientation="portrait">

14 <activity android:name=".placeholderActivity1" android:screenOrientation="portrait">

15 <activity android:name=".placeholderActivity2" android:screenOrientation="portrait">

16             <intent-filter>

17                 <action android:name="android.intent.action.MAIN" />

18                 <category android:name="android.intent.category.LAUNCHER" />

19             </intent-filter>

20                 </activity>

21

22     </application>

23     <uses-sdk android:minSdkVersion="4" />

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 21: Android Adapters, An Introduction

24 </manifest>

List View and List Adapter

If you want to show a List, there are two ways to do that: ListView and ListActivity. Both ListView and ListActivity can add items by using ListAdapter. There are many kinds of ListAdapter, which are shown in the list below:

ArrayAdapter<T> : A ListAdapter that manages a ListView backed by an array of arbitrary objects. BaseAdapter : Common base class of common implementation for an Adapter that can be used in both

ListView and Spinner. CursorAdapter : Adapter that exposes data from a Cursor to a ListView widget. HeaderViewListAdapter : ListAdapter used when a ListView has header views. ResourceCursorAdapter : An easy adapter that creates views defined in an XML file. SimpleAdapter : An easy adapter to map static data to views defined in an XML file. SimpleCursorAdapter : An easy adapter to map columns from a cursor to TextViews or ImageViews

defined in an XML file. WrapperListAdapter : List adapter that wraps another list adapter. The wrapped adapter can be retrieved

by calling !getWrappedAdapter(). ListAdapter : Extended Adapter that is the bridge between a ListView and the data that backs the list.

Define a ListView

When you want to display your list, you should define a ListView in one of xml files that you want to show. An example is given below.

<ListView android:id="@+id/test_list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dpi" android:layout_marginRight="10dpi" android:layout_marginTop="10dpi" android:layout_marginBottom="10dpi"android:visibility="invisible" android:cacheColorHint="#00000000"></ListView>

As you can see, you can define width/height, margin in each direction, and visibility. When the user chooses a list item, sometimes that list item is shown as black. If you want to prevent this, you can use 'cacheColorHint'.

Fill out your list

Ones you define a ListView, you can fill out that ListView by using ListAdapter objects. There are also two ways to fill out your list: making your own rows and using the default layout.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 22: Android Adapters, An Introduction

Using the Default Layout

These are layouts that already-defined at Android.R.layout and you can use at ListAdapter. Here is the example by using one of default layout 'simple_list_item_1'

Toggle line numbers

1 ListView list = (ListView)findViewById(R.id.test_list); 2 3 list.setAdapter(new ArrayAdapter<String>(this, 4 android.R.layout.simple_list_item_1, mStrings)); 5 6 list.setTextFilterEnabled(true);

mStrings are string array that has information, and I use ArrayAdapter for fill out.

make your own row

You can also make your own row for displaying a list.

File name : row.xml

<?xml version="1.0" encoding="utf-8"?><AbsoluteLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"><TextView

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 23: Android Adapters, An Introduction

android:id="@+id/Name"android:layout_width="200dip"android:layout_height="wrap_content"android:text="Country"android:textSize="20sp"android:typeface="sans"android:textStyle="bold"android:gravity="center"android:layout_x="0dip"android:layout_y="0dip"></TextView><TextViewandroid:id="@+id/currencyValue"android:layout_width="100dip"android:layout_height="wrap_content"android:text="currency"android:textSize="20sp"android:typeface="serif"android:textStyle="italic"android:layout_x="200dip"android:layout_y="0dip"android:gravity="right"></TextView></AbsoluteLayout>

I defined two text view for displaying each counties name and vaule. After you defined these value, you can fill out your list.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 24: Android Adapters, An Introduction

Toggle line numbers

1 ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); 2 3 HashMap<String, String> item; 4 for (int i = 0; i < 31; i++) { 5 item = new HashMap<String, String>(); 6 item.put("Name", "Any names are possible~~~~" ); 7 item.put("currencyValue", "Any string values are possible" ); 8 list.add(item); 9 } 10 11 SimpleAdapter notes = new SimpleAdapter(this, list, R.layout.row, 12 new String[] { "Name", "currencyValue" }, new int[] {R.id.Name, R.id.currencyValue }); 13 setListAdapter(notes);

This time I use SimpleAdapter inside of ListActivity. The structure of SimpleAdapter class is (activity, ArrayList<Hashmap<String, (some_type)>> ,layout,keys for hashing(String array), IDs that are mapped(int array))

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 25: Android Adapters, An Introduction

Add a cursor

Now, you can display your list, but you program will do nothing when user choose one list item from your list. But once you write OnListItemClick function, you can make a new action(make an intent for changing page/moving info/etc).

Toggle line numbers

1 @Override 2 protected void onListItemClick(ListView listView, View view, int position, long id) { 3 super.onListItemClick(listView, view, position, id); 4 // do anything that you want!! 5 }

Here is an example by using cursor.

Toggle line numbers

1 private SimpleCursorAdapter myAdapter; 2 3 @Override 4 public void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null); 7 startManagingCursor(cursor); 8 9 String[] columns = new String[] {People.NAME, People.NUMBER}; 10 int[] names = new int[] {R.id.contact_name, R.id.phone_number}; 11 12 myAdapter = new SimpleCursorAdapter(this, R.layout.contact, cursor, columns, names); 13 setListAdapter(myAdapter); 14 } 15 16 @Override 17 protected void onListItemClick(ListView listView, View view, int position, long id) { 18 super.onListItemClick(listView, view, position, id); 19 20 //Switch to second page when next button is clicked 21 Intent i = new Intent(); 22 Bundle extras = getIntent().getExtras(); 23 Cursor cursor = (Cursor) myAdapter.getItem(position); 24 25 //define which page is next 26 i.setClassName("com.sms.Arabic", "com.sms.Arabic.SMSSender"); 27 //add data to intent as extras 28 StringBuilder app = new StringBuilder(""); 29 30 if(!extras.getString("sender").equals("")){ 31 app.append(extras.getString("sender")); 32 app.append(";"); 33 } 34 35 String phoneNum = cursor.getString(cursor.getColumnIndex(People.NUMBER));

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 26: Android Adapters, An Introduction

36 if(phoneNum!=null){ 37 phoneNum = number_modify(phoneNum); 38 app.append(phoneNum); 39 i.putExtra("sender", app.toString()); 40 //start the next activity, and have it return a result 41 startActivity(i); 42 finish(); 43 } 44 else{ 45 Toast.makeText(this, "This contacts has no number", Toast.LENGTH_SHORT).show(); 46 } 47 }

This example queries all of the contact list, and displays all of them. This time I use a SimpleCursorAdapter inside a ListActivity. (The format of SimpleCursorAdapter is (ListActivity, layout file name, cursor, columns(String array), names for matching(int array)) ) When the user click one of the list, it create an activity with selected contact information.

ArrayAdapter: A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView.

arrayadapter.

Android AutoCompleteTextView Example

February 10, 2010 in Android Tutorial, AutoCompleteTextView, Textview by Sasikumar

In android, we can show a string items in autocompletetextview. So that items will display according to the characters we have give.Ex:- If we are giving ‘an’ it will show all the items starts with ‘an’.Example for AutoCompleteTextView :-

view source

print ?

01 <?xml version="1.0" encoding="utf-8"?>

02 <LinearLayout android:id="@+id/LinearLayout01"

03 android:layout_width="fill_parent"

04 android:layout_height="fill_parent"

05 xmlns:android="http://schemas.android.com/apk/res/android">

06 <AutoCompleteTextView

07 android:id="@+id/AutoCompleteTextView01"

08 android:layout_width="wrap_content"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 27: Android Adapters, An Introduction

09 android:layout_height="wrap_content"

10 android:hint="This is Hint"

11 android:width="240px" />

12 </LinearLayout>

view source

print ?

01 public class ExampleApp extends Activity

02 {

03     @Override

04     protected void onCreate(Bundle savedInstanceState) {

05         super.onCreate(savedInstanceState);

06         setContentView(R.layout.main);

07         ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(this,

08                 android.R.layout.simple_dropdown_item_1line, sampleACTV);

09         AutoCompleteTextView ACTV = (AutoCompleteTextView)

10                 findViewById(R.id.AutoCompleteTextView01);

11         ACTV.setAdapter(arrAdapter);

12     }

13     private static final String[] sampleACTV = new String[] {

14         "android","androidpeople.com","iphone","blackberry"

15     };

16 }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 28: Android Adapters, An Introduction

The output will looks like

1 ► Retweet

Tags: android, arrayadapter, AutoCompleteTextView, code, example, how to, source, TextviewComments (6)

Android Listview Example

January 22, 2010 in Android Tutorial, Listview, Scroll, Tutorial by Sasikumar

Today, we are going to see about a simple listview example. In Android, Listview is used to show a list of items in a vertically scrolling list.  Learn a listview of android array in this tutorial.

For instance, in a Registration form when we are selecting professions a list of items will be displayed. We can use Listview to display the list of items.

Your XML file should look like

view source

print ?

1 <?xml version="1.0" encoding="utf-8"?>

2 <LinearLayout android:id="@+id/LinearLayout01"

3  android:layout_width="fill_parent"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 29: Android Adapters, An Introduction

4  android:layout_height="fill_parent"

5  xmlns:android="http://schemas.android.com/apk/res/android">

6  <ListView android:id="@+id/ListView01"

7  android:layout_width="wrap_content"

8  android:layout_height="wrap_content" />

9 </LinearLayout>

Your Java code looks like

view source

print ?

01 public class ListviewExample extends Activity

02 {

03 private ListView lv1;

04 private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};

05 @Override

06 public void onCreate(Bundle icicle)

07 {

08 super.onCreate(icicle);

09 setContentView(R.layout.main);

10 lv1=(ListView)findViewById(R.id.ListView01);

11 // By using setAdpater method in listview we an add string array in list.

12lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));

13 }

14 }

You can also customize your listview. Click here to see custom listview example

The output will look like

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 30: Android Adapters, An Introduction

► Retweet

Tags: adapter, android, array, arrayadapter, code, example, how to, list, Listview, source, viewComments (62)

Android Spinner Example

January 6, 2010 in Android Tutorial, Spinner, Tutorial by admin

In Android, Spinner is nothing but a combo box or list box.

It lets you viewing multiple items and allows you to select one item from the list.

Edit Your XML code like this

view source

print ?

1 <Spinner android:id="@+id/Spinner01"

2 android:layout_width="wrap_content"

3 android:layout_height="wrap_content" />

Your Java Class code should look like this

view source

print ?

01 public class SpinnerExample extends Activity {

02 private String array_spinner[];

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 31: Android Adapters, An Introduction

03     @Override

04     public void onCreate(Bundle savedInstanceState) {

05         super.onCreate(savedInstanceState);

06         setContentView(R.layout.main);

07         array_spinner=new String[5];

08         array_spinner[0]="1";

09         array_spinner[1]="2";

10         array_spinner[2]="3";

11         array_spinner[3]="4";

12         array_spinner[4]="5";

13         Spinner s = (Spinner) findViewById(R.id.Spinner01);

14         ArrayAdapter adapter = new ArrayAdapter(this,

15                 android.R.layout.simple_spinner_item, array_spinner);

16         s.setAdapter(adapter);

17     }

18 }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 32: Android Adapters, An Introduction

The Output will look like

[Android] Using an ArrayAdapter to Control a ListView’s Data

Data inside a ListView supplied by a ListAdapter. The manipulation of data, such as adding and removing items, is done through the adapter. The adapter will automatically make the ListView update itself to correspond to the change. The source for the list is set with by calling setAdapter with the source adapter. In this tutorial, an ArrayAdapter is used with a ListView.

The code for the following example is downloaded from here. The example uses a ListActivity to provide a ListView:

view source

print ?

01 private ArrayAdapter<String> dataAdapter;

02

03 /** Called when the activity is first created. */

04 @Override

05 public void onCreate(Bundle savedInstanceState)

06 {

07     super.onCreate(savedInstanceState);

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 33: Android Adapters, An Introduction

08

09     dataAdapter = new ArrayAdapter<String>(this, R.layout.item,

10         R.id.itemName);

11     dataAdapter.add("apple");

12     dataAdapter.add("orange");

13     dataAdapter.add("tomato");

14

15     setListAdapter(dataAdapter);

16 }

A ListActivity is a form of Activity, but automatically provides a ListView. The method setListAdapter is provided by the ListActivity class and will set the adapter of the ListView. Running this code alone should produce a list looking like this:

The activity also provides an options menu that is accessible when the menu key is pressed. Accessible from the menu is the option to add and remove items from the list. Selecting the add options pops open the following dialog:

The code that actually adds the contents from the dialog to the ListView is inside the DialogInterface.OnClickListener associated with the add button:

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 34: Android Adapters, An Introduction

view source

print ?

01 builder.setPositiveButton(R.string.addButtonLabel,

02     new DialogInterface.OnClickListener()

03 {

04

05     public void onClick(DialogInterface dialog, int which)

06     {

07         Dialog source = (Dialog) dialog;

08         EditText nameField = (EditText) source

09             .findViewById(R.id.itemField);

10         String name = nameField.getText().toString();

11

12         EditText timesField = (EditText) source

13             .findViewById(R.id.timesField);

14         Integer times = Integer.valueOf(timesField.getText()

15             .toString());

16

17         if ((name.length() > 0) && (times > 0))

18         {

19             for (int count = 0; count < times; count++)

20             {

21                 dataAdapter.add(name);

22             }

23         }

24         dialog.dismiss();

25     }

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 35: Android Adapters, An Introduction

26 });

Lines 8 to 10 is just getting the string to add to the list. Lines 12 to 15 is getting the value in the times field. In Lines 17 to 23, if the item is given and the specified number of times is greater than zero, then the item is added however many times was specified. Line 21 is where the item is actually added to the list. Notice that the item is added to the adapter, not the view. This is ALL that is required to make the item to add to the list. Since back in onCreate, the adapter was already set as the ListView’s adapter, will automatically cause the ListView to update.

Selecting the remove option on the menu removes the last item from the list. As there is no dialog required, the code that does this is back in onOptionsItemSelected. More specifically, it is done by this part of the method:

1 case REMOVE_ITEM:

2     dataAdapter.remove(

3         dataAdapter.getItem(

4             dataAdapter.getCount() - 1));

5     break;

Again, notice that the item is removed by calling remove on the adapter, not the ListView. The view is automatically updated when the item is removed.

PROGRAM

Src

import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.app.ListActivity;import android.content.DialogInterface;import android.content.res.Resources;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.EditText;

public class ArrayAdapterData extends ListActivity{ private static final int ADD_ITEM = 0; private static final int REMOVE_ITEM = 1; private static final int EXIT_ITEM = 2;

private ArrayAdapter<String> dataAdapter; private Dialog editorDialog = null;

/** Called when the activity is first created. */

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 36: Android Adapters, An Introduction

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

dataAdapter = new ArrayAdapter<String>(this, R.layout.item, R.id.itemName); dataAdapter.add("apple"); dataAdapter.add("orange"); dataAdapter.add("tomato");

setListAdapter(dataAdapter); }

public boolean onCreateOptionsMenu(Menu menu) { Resources resource = getApplicationContext().getResources(); menu.add(Menu.NONE, ADD_ITEM, ADD_ITEM, resource.getText(R.string.ADD_ITEM)).setIcon(R.drawable.add); menu.add(Menu.NONE, REMOVE_ITEM, REMOVE_ITEM, resource.getText(R.string.REMOVE_ITEM)).setIcon(R.drawable.remove); menu.add(Menu.NONE, EXIT_ITEM, EXIT_ITEM, resource.getText(R.string.EXIT_ITEM)).setIcon(R.drawable.exit); return true; }

public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case ADD_ITEM: showDialog(0); break; case REMOVE_ITEM: dataAdapter.remove(dataAdapter.getItem(dataAdapter.getCount() - 1)); break; case EXIT_ITEM: finish(); } return false; }

@Override protected Dialog onCreateDialog(int id) { Dialog editor = editorDialog; if (editorDialog == null) { editor = createEditorDialog(); } return editor; }

private Dialog createEditorDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.addDialogTitle);

View content = getLayoutInflater().inflate(R.layout.editor, (ViewGroup) findViewById(R.id.editLayout)); builder.setView(content);

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 37: Android Adapters, An Introduction

builder.setPositiveButton(R.string.addButtonLabel, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) { Dialog source = (Dialog) dialog; EditText nameField = (EditText) source .findViewById(R.id.itemField); String name = nameField.getText().toString();

EditText timesField = (EditText) source .findViewById(R.id.timesField); Integer times = Integer.valueOf(timesField.getText() .toString());

if ((name.length() > 0) && (times > 0)) { for (int count = 0; count < times; count++) { dataAdapter.add(name); } } dialog.dismiss(); } });

builder.setNegativeButton(R.string.cancelButtonLabel, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } });

return builder.create(); }}

Layout

Editor.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/editLayout" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical">

<TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:orientation="horizontal" android:padding="5dp" gravity="center_horizontal">

<TableRow android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center_horizontal">

<TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/nameLabel"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 38: Android Adapters, An Introduction

android:text="@string/nameLabel" android:gravity="right|center_vertical" android:layout_marginRight="5dp" />

<EditText android:layout_height="fill_parent" android:id="@+id/itemField" android:layout_width="fill_parent" android:width="200dp" /> </TableRow> </TableLayout>

<LinearLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="horizontal" android:gravity="center_horizontal">

<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/timesLabel" android:text="@string/timesLabel" android:gravity="right|center_vertical" android:layout_marginRight="5dp" />

<EditText android:text="1" android:id="@+id/timesField" android:width="100dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:digits="0123456789" /> </LinearLayout>

</LinearLayout>

Item.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" android:paddingLeft="5dp"android:paddingRight="5dp">

<TextView android:id="@+id/itemName" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="Test view" />

</LinearLayout>

Values

String.xml

<?xml version="1.0" encoding="utf-8"?><resources> <string name="applicationName">String List</string>

<string name="priceFormat">{0,number, currency}</string>

<!-- Options menu --> <string name="ADD_ITEM">Add to End</string> <string name="REMOVE_ITEM">Remove Last</string> <string name="EXIT_ITEM">Exit</string>

<!-- Parameters for the "Add Item" dialog --> <string name="addDialogTitle">Add Item</string> <string name="nameLabel">Item </string> <string name="priceLabel">Price </string> <string name="timesLabel">Times</string>

<!-- Labels for the button -->

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 39: Android Adapters, An Introduction

<string name="addButtonLabel">Add</string> <string name="cancelButtonLabel">Cancel</string></resources>

CursorAdapter: Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work.

Monday, August 10, 2009

Custom View in your ListActivity and Custom Adapter in Android

After 2-3 weeks of being absent in Android land, due to over working (going home pass 12am.......), i'm back with another tutorial on how to make your ListActivity have a view that you like or custom view. In order for us to jump right ahead, you must first know that custom view on your ListActivity means custom view per row on the ListView and usually we need to create or its better to create a custom adapter for it.

For this tutorial, i would reference to the Display Contact Names in Android therefore we need to add READ_CONTACTS on our manifest file.

On our custom_list.xml we would have<?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:id="@+id/txtName"  />

  <TextView    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/txtPhone"  />

  <TextView    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/txtDisplayName"  /></LinearLayout>

Explanation

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 40: Android Adapters, An Introduction

This would just give us 3 TextView on vertical order, this would be our custom row therefore on your application if you want to customize the row then this is the file that you might want to work upon.

Main.javapublic class Main extends ListActivity {  @Override  public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    Cursor contactsCursor = this.managedQuery(People.CONTENT_URI, null, null, null, null);    this.setListAdapter(new MyContactsAdapter(this,contactsCursor));  }

  private class MyContactsAdapter extends CursorAdapter{    private Cursor mCursor;    private Context mContext;    private final LayoutInflater mInflater;

    public MyContactsAdapter(Context context, Cursor cursor) {      super(context, cursor, true);      mInflater = LayoutInflater.from(context);      mContext = context;    }

    @Override    public void bindView(View view, Context context, Cursor cursor) {      TextView t = (TextView) view.findViewById(R.id.txtName);      t.setText(cursor.getString(cursor.getColumnIndex(People.NAME)));

      t = (TextView) view.findViewById(R.id.txtDisplayName);      t.setText(cursor.getString(cursor.getColumnIndex(People.DISPLAY_NAME)));

      t = (TextView) view.findViewById(R.id.txtPhone);      t.setText(cursor.getString(cursor.getColumnIndex(People.NUMBER)));    }

    @Override    public View newView(Context context, Cursor cursor, ViewGroup parent) {      final View view = mInflater.inflate(R.layout.custom_list, parent, false);      return view;    }  }}

ExplanationQuery our contacts tableCursor contactsCursor = this.managedQuery(People.CONTENT_URI, null, null, null, null);

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 41: Android Adapters, An Introduction

Set the adapter for our ListViewthis.setListAdapter(new MyContactsAdapter(this,contactsCursor));

We create a class for our custom adapter named MyContactsAdapter extending it to CursorAdapter (There are a lot of adapter that you could extend upon)private class MyContactsAdapter extends CursorAdapter

We get the LayoutInflater from the calling context, what this does is that it will inflate your xml to codes via View object. see newView functionmInflater = LayoutInflater.from(context);

On newView function we inflate our layout to the binded view inside CursorAdapterfinal View view = mInflater.inflate(R.layout.custom_list, parent, false);

At this point we have our custom_list as the layout of our ListActivity, now what we need is to use it on every row, you would do it with bindView functionpublic void bindView(View view, Context context, Cursor cursor) { ..... }

The following should be just binding our TextView in xml to our codes and getting values from our cursor and putting that value to the respective TextViewTextView t = (TextView) view.findViewById(R.id.txtName);t.setText(cursor.getString(cursor.getColumnIndex(People.NAME)));

NotesDo note that we extend to CursorAdapter here and it might be different on other adapter, like for ArrayAdapter you will use getView function, good luck....

HeaderViewListAdapter: ListAdapter used when a ListView has header views. This

ListAdapter wraps another one and also keeps track of the header views and their associated data objects.This is intended as a base class; you will probably not need to use this class directly in your own code.

ResourceCursorAdapter: An easy adapter that creates views defined in an XML file. You can

specify the XML file that defines the appearance of the views.

Class: android.widget.ResourceCursorAdapter

public abstract class ResourceCursorAdapter extends CursorAdapter

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 42: Android Adapters, An Introduction

An easy adapter that creates views defined in an XML file. You can specify the XML file that defines the appearance of the views.

InheritanceSuperclass tree:

java.lang.Object android.widget.BaseAdapter android.widget.CursorAdapter android.widget.ResourceCursorAdapter

Implements:

Filterable ListAdapter SpinnerAdapter Adapter

Methods

ResourceCursorAdaptertop

public ResourceCursorAdapter(Context context, int layout, Cursor c)

Constructor.

Parameters:

@param context The context where the ListView associated with this SimpleListItemFactory is running

@param layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

Related Links:

Google Code Search

Stack Overflow

ResourceCursorAdaptertop

public ResourceCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery)

Constructor.

Parameters:

@param context The context where the ListView associated with this SimpleListItemFactory is running

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 43: Android Adapters, An Introduction

@param layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

@param c The cursor from which to get the data.

@param autoRequery If true the adapter will call requery() on the cursor whenever it changes so the most recent data is always displayed.

Related Links:

Google Code Search

Stack Overflow

newDropDownViewtopo @Override

public View newDropDownView(Context context, Cursor cursor, ViewGroup parent)

Makes a new drop down view to hold the data pointed to by cursor.

Parameters:

@param context Interface to application's global information

@param cursor The cursor from which to get the data. The cursor is already moved to the correct position.

@param parent The parent to which the new view is attached to

Return:

@return the newly created view.

Override hierarchy:

newDropDownView from CursorAdapter

Related Links:

Google Code Search

Stack Overflow

newViewtopo @Override

public View newView(Context context, Cursor cursor, ViewGroup parent)

Inflates view(s) from the specified XML file.

Parameters:

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 44: Android Adapters, An Introduction

@param context Interface to application's global information

@param cursor The cursor from which to get the data. The cursor is already moved to the correct position.

@param parent The parent to which the new view is attached to

Return:

@return the newly created view.

See:

@see android.widget.CursorAdapter.newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)

Override hierarchy:

newView from CursorAdapter

Related Links:

Google Code Search

Stack Overflow

setDropDownViewResourcetop

public void setDropDownViewResource(int dropDownLayout)

Sets the layout resource of the drop down views.

Parameters:

@param dropDownLayout the layout resources used to create drop down views

Related Links:

Google Code Search

Stack Overflow

setViewResourcetop

public void setViewResource(int layout)

Sets the layout resource of the item views.

Parameters:

@param layout the layout resources used to create item views

Related Links:

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 45: Android Adapters, An Introduction

Google Code Search

Stack Overflow

History

ResourceCursorAdapter

Methods

Constructors

ResourceCursorAdapter(Context,int,Cursor) ResourceCursorAdapter(Context,int,Cursor,boolean)

Members [ +/- ]

areAllItemsEnabled():boolean bindView(View,Context,Cursor):void changeCursor(Cursor):void convertToString(Cursor):CharSequence equals(Object):boolean getClass():Class<? extends Object> getCount():int getCursor():Cursor getDropDownView(int,View,ViewGroup):View getFilter():Filter getFilterQueryProvider():FilterQueryProvider getItem(int):Object getItemId(int):long getItemViewType(int):int getView(int,View,ViewGroup):View getViewTypeCount():int hasStableIds():boolean hashCode():int isEmpty():boolean isEnabled(int):boolean newDropDownView(Context,Cursor,ViewGroup):View newView(Context,Cursor,ViewGroup):View notify():void notifyAll():void notifyDataSetChanged():void notifyDataSetInvalidated():void registerDataSetObserver(DataSetObserver):void runQueryOnBackgroundThread(CharSequence):Cursor setDropDownViewResource(int):void setFilterQueryProvider(FilterQueryProvider):void setViewResource(int):void toString():String unregisterDataSetObserver(DataSetObserver):void wait():void

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 46: Android Adapters, An Introduction

wait(long):void wait(long,int):void

Inheritance

Implements

Adapter SpinnerAdapter ListAdapter Filterable

Extends

Object BaseAdapter CursorAdapter

Class

ResourceCursorAdapter

Children

SimpleCursorAdapter

ResourceCursorAdapterextends CursorAdapter

java.lang.Object

↳ android.widget.BaseAdapter

↳ android.widget.CursorAdapter

↳ android.widget.ResourceCursorAdapter

Known Direct Subclasses

SimpleCursorAdapter

SimpleCursorAdapterAn easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file.

Class Overview

An easy adapter that creates views defined in an XML file. You can specify the XML file that defines the appearance of the views.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 47: Android Adapters, An Introduction

Summary[Expand]

Inherited Constants

From interface android.widget.Adapter

int IGNORE_ITEM_VIEW_TYPE An item view type that causes the AdapterView to ignore the item view.

int NO_SELECTION

Public Constructors

ResourceCursorAdapter(Context context, int layout, Cursor c)

Constructor.

ResourceCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery)

Constructor.

Public Methods

View newDropDownView(Context context, Cursor cursor, ViewGroup parent)

Makes a new drop down view to hold the data pointed to by cursor.

View newView(Context context, Cursor cursor, ViewGroup parent)

Inflates view(s) from the specified XML file.

void setDropDownViewResource(int dropDownLayout)

Sets the layout resource of the drop down views.

void setViewResource(int layout)

Sets the layout resource of the item views.[Expand]

Inherited Methods

From class android.widget.CursorAdapter

abstract void bindView(View view, Context context, Cursor cursor)

Bind an existing view to the data pointed to by cursor

void changeCursor(Cursor cursor)

Change the underlying cursor to a new cursor.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 48: Android Adapters, An Introduction

CharSequence convertToString(Cursor cursor)

Converts the cursor into a CharSequence.int getCount()

Cursor getCursor()

Returns the cursor.

View getDropDownView(int position, View convertView, ViewGroup parent)

Get a View that displays in the drop down popup the data at the specified position in the data set.

Filter getFilter()

Returns a filter that can be used to constrain data with a filtering pattern.

FilterQueryProvider getFilterQueryProvider()

Returns the query filter provider used for filtering.

Object getItem(int position)

long getItemId(int position)

View getView(int position, View convertView, ViewGroup parent)

boolean hasStableIds()

Indicated whether the item ids are stable across changes to the underlying data.

void init(Context context, Cursor c, boolean autoRequery)

View newDropDownView(Context context, Cursor cursor, ViewGroup parent)

Makes a new drop down view to hold the data pointed to by cursor.

abstract View newView(Context context, Cursor cursor, ViewGroup parent)

Makes a new view to hold the data pointed to by cursor.

void onContentChanged()

Called when the ContentObserver on the cursor receives a change notification.

Cursor runQueryOnBackgroundThread(CharSequence constraint)

Runs a query with the specified constraint.

void setFilterQueryProvider(FilterQueryProvider filterQueryProvider)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 49: Android Adapters, An Introduction

Sets the query filter provider used to filter the current Cursor.

From class android.widget.BaseAdapter

boolean areAllItemsEnabled()

Are all items in this ListAdapter enabled? If yes it means all items are selectable and clickable.

View getDropDownView(int position, View convertView, ViewGroup parent)

Get a View that displays in the drop down popup the data at the specified position in the data set.

int getItemViewType(int position)

Get the type of View that will be created by getView(int, View, ViewGroup) for the specified item.

int getViewTypeCount()

Returns the number of types of Views that will be created by getView(int, View, ViewGroup).

boolean hasStableIds()

Indicated whether the item ids are stable across changes to the underlying data.

boolean isEmpty()

boolean isEnabled(int position)

Returns true if the item at the specified position is not a separator.

void notifyDataSetChanged()

Notifies the attached View that the underlying data has been changed and it should refresh itself.

void notifyDataSetInvalidated()

void registerDataSetObserver(DataSetObserver observer)

Register an observer that is called when changes happen to the data used by this adapter.

void

unregisterDataSetObserver(DataSetObserver observer)

Unregister an observer that has previously been registered with this adapter via registerDataSetObserver(DataSetObserver).

From class java.lang.Object

Object clone()

Creates and returns a copy of this Object.

boolean equals(Object o)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 50: Android Adapters, An Introduction

Compares this instance with the specified object and indicates if they are equal.

void finalize()

Is called before the object's memory is being reclaimed by the VM.

final Class<? extends Object>

getClass()

Returns the unique instance of Class which represents this object's class.

int hashCode()

Returns an integer hash code for this object.

final void

notify()

Causes a thread which is waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

final void

notifyAll()

Causes all threads which are waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up.

String toString()

Returns a string containing a concise, human-readable description of this object.

final void

wait(long millis, int nanos)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

final void

wait(long millis)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the specified timeout expires.

final void

wait()

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

From interface android.widget.Adapter

abstract int

getCount()

How many items are in the data set represented by this Adapter.

abstract Object

getItem(int position)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 51: Android Adapters, An Introduction

Get the data item associated with the specified position in the data set.

abstract long

getItemId(int position)

Get the row id associated with the specified position in the list.

abstract int

getItemViewType(int position)

Get the type of View that will be created by getView(int, View, ViewGroup) for the specified item.

abstract View

getView(int position, View convertView, ViewGroup parent)

Get a View that displays the data at the specified position in the data set.

abstract int

getViewTypeCount()

Returns the number of types of Views that will be created by getView(int, View, ViewGroup).

abstract boolean

hasStableIds()

Indicated whether the item ids are stable across changes to the underlying data.

abstract boolean

isEmpty()

abstract void

registerDataSetObserver(DataSetObserver observer)

Register an observer that is called when changes happen to the data used by this adapter.

abstract void

unregisterDataSetObserver(DataSetObserver observer)

Unregister an observer that has previously been registered with this adapter via registerDataSetObserver(DataSetObserver).

From interface android.widget.Filterable

abstract Filter

getFilter()

Returns a filter that can be used to constrain data with a filtering pattern.From interface android.widget.ListAdapter

abstract boolean

areAllItemsEnabled()

Are all items in this ListAdapter enabled? If yes it means all items are selectable and clickable.

abstract boolean

isEnabled(int position)

Returns true if the item at the specified position is not a separator.

From interface android.widget.SpinnerAdapter

abstract getDropDownView(int position, View convertView, ViewGroup parent)

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 52: Android Adapters, An Introduction

View

Get a View that displays in the drop down popup the data at the specified position in the data set.

Public Constructors

public ResourceCursorAdapter (Context context, int layout, Cursor c)

Since: API Level 1

Constructor.

Parameterscontext The context where the ListView associated with this SimpleListItemFactory is running

layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

public ResourceCursorAdapter (Context context, int layout, Cursor c, boolean autoRequery)

Since: API Level 3

Constructor.

Parameterscontext The context where the ListView associated with this SimpleListItemFactory is running

layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

c The cursor from which to get the data.

autoRequery If true the adapter will call requery() on the cursor whenever it changes so the most recent data is always displayed.

Public Methods

public View newDropDownView (Context context, Cursor cursor, ViewGroup parent)

Since: API Level 1

Makes a new drop down view to hold the data pointed to by cursor.

Parameterscontext Interface to application's global information

cursor The cursor from which to get the data. The cursor is already moved to the correct position.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 53: Android Adapters, An Introduction

parent The parent to which the new view is attached to

Returns

the newly created view.

public View newView (Context context, Cursor cursor, ViewGroup parent)

Since: API Level 1

Inflates view(s) from the specified XML file.

Parameterscontext Interface to application's global information

cursor The cursor from which to get the data. The cursor is already moved to the correct position.

parent The parent to which the new view is attached to

Returns

the newly created view.

See Also

newView(android.content.Context, android.database.Cursor, ViewGroup)

public void setDropDownViewResource (int dropDownLayout)

Since: API Level 1

Sets the layout resource of the drop down views.

ParametersdropDownLayout the layout resources used to create drop down views

public void setViewResource (int layout)

Since: API Level 3

Sets the layout resource of the item views.

Parameterslayout the layout resources used to create item views

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 54: Android Adapters, An Introduction

android.widget.ResourceCursorAdapterpackage android.widget;

18

 

19

 import android.content.Context;

20

 import android.database.Cursor;

21

 import android.view.View;

22

 import android.view.ViewGroup;

23

 import android.view.LayoutInflater;

An easy adapter that creates views defined in an XML file. You can specify the XML file that defines the appearance of the views.

29

 

30

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 55: Android Adapters, An Introduction

 public abstract class  ResourceCursorAdapter extends CursorAdapter {

31

     private int mLayout;

32

 

33

     private int mDropDownLayout;

34

     

35

     private LayoutInflater mInflater;        Constructor.

Parameters:

context The context where the ListView associated with this SimpleListItemFactory is running

layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

45

 

46

     public  ResourceCursorAdapter(Context context, int layout, Cursor c) {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 56: Android Adapters, An Introduction

47

         super(context, c);

48

         mLayout = mDropDownLayout = layout;

49

         mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

50

     }        Constructor.

Parameters:

context The context where the ListView associated with this SimpleListItemFactory is running

layout resource identifier of a layout file that defines the views for this list item. Unless you override them later, this will define both the item views and the drop down views.

c The cursor from which to get the data.

autoRequery If true the adapter will call requery() on the cursor whenever it changes so the most recent data is always displayed.

64

 

65

     public ResourceCursorAdapter(Context context, int layout, Cursor c, boolean autoRequery) {

66

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 57: Android Adapters, An Introduction

         super(context, c, autoRequery);

67

         mLayout = mDropDownLayout = layout;

68

         mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

69

     }

    Inflates view(s) from the specified XML file.

See also:

CursorAdapter.newView(android.content.Context,android.database.Cursor,android.view.ViewGroup)

76

 

77

     @Override

78

     public View  newView(Context context, Cursor cursor, ViewGroup parent) {

79

         return mInflater.inflate(mLayout, parent, false);

80

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 58: Android Adapters, An Introduction

     }

81

 

82

     @Override

83

     public View  newDropDownView(Context context, Cursor cursor, ViewGroup parent) {

84

         return mInflater.inflate(mDropDownLayout, parent, false);

85

     }

    

Sets the layout resource of the item views.

Parameters:

layout the layout resources used to create item views

     public void  setViewResource(int layout) {

         mLayout = layout;

94

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 59: Android Adapters, An Introduction

     }        

Sets the layout resource of the drop down views.

Parameters:

dropDownLayout the layout resources used to create drop down views

100

101

    public void  setDropDownViewResource(int dropDownLayout) {

102

        mDropDownLayout = dropDownLayout;

103

    }

104

}

SimpleAdapter: An easy adapter to map static data to views defined in an XML file. You can

specify the data backing the list as an ArrayList of Maps. Each entry in the ArrayList corresponds to one row in the list.

Use SimpleAdapter to make a list with icons July 30th, 2010

Here's another way to make a simple list, whose items have an icon and a line of text. Use SimpleAdapter and the list item layout is a TextView.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 60: Android Adapters, An Introduction

res/layout/list_item.xml:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/list_text" android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:textAppearance="?android:attr/textAppearanceLarge"

android:gravity="center_vertical" android:paddingLeft="5dip" android:minHeight="?android:attr/listPreferredItemHeight"

android:drawableLeft="@drawable/icon"

android:drawablePadding="10dip"/>

IconList.java

package com.kurtchen.android.iconlist;

import android.app.ListActivity;

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 61: Android Adapters, An Introduction

import android.os.Bundle;import android.view.View;

import android.widget.SimpleAdapter;

import android.widget.TextView;import android.widget.SimpleAdapter.ViewBinder;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;import java.util.Map;

public class IconListActivity extends ListActivity implements ViewBinder {

private static final String LIST_TEXT = "list_text";

/** Called when the activity is first created. */

@Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

initList();

}

private void initList() { List<Map<String, ListItem>> listData = new ArrayList<Map<String, ListItem>>(3);

Map<String, ListItem> itemData1 = new HashMap<String, ListItem>(1); ListItem listItem1 = new ListItem(); listItem1.text = getString(R.string.menu_item1); listItem1.icon = R.drawable.facebook; itemData1.put(LIST_TEXT, listItem1);

listData.add(itemData1);

Map<String, ListItem> itemData2 = new HashMap<String, ListItem>(1); ListItem listItem2 = new ListItem();

listItem2.text = getString(R.string.menu_item1);

listItem2.icon = R.drawable.flickr;

itemData2.put(LIST_TEXT, listItem2); listData.add(itemData2);

Map<String, ListItem> itemData3 = new HashMap<String, ListItem>(1);

ListItem listItem3 = new ListItem();

listItem3.text = getString(R.string.menu_item1); listItem3.icon = R.drawable.twitter; itemData3.put(LIST_TEXT, listItem3);

listData.add(itemData3);

SimpleAdapter simpleAdapter = new SimpleAdapter(this, listData,

R.layout.list_item,

new String[] {

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 62: Android Adapters, An Introduction

LIST_TEXT }, new int[] {

R.id.list_text

}); simpleAdapter.setViewBinder(this);

setListAdapter(simpleAdapter); }

@Override public boolean setViewValue(View view, Object data, String stringRepresetation) {

ListItem listItem = (ListItem)data;

TextView menuItemView = (TextView)view;

menuItemView.setText(listItem.text);

menuItemView.setCompoundDrawablesWithIntrinsicBounds(this.getResources().getDrawable( listItem.icon), null, null, null);

return true; }

private class ListItem { public String text;

public int icon;

}}

SimpleAdapter, as its name indicated, is just a simple implementation. If we want to make changes in list dynamically, we may need to write a custom adaptor.

SimpleCursorAdapter: An easy adapter to map columns from a cursor to TextViews or ImageViews defined in an XML file. You can specify which columns you want, which views you want to display the columns, and the XML file that defines the appearance of these views.

SpinnerAdapter: Extended Adapter that is the bridge between a Spinner and its data. A spinner adapter allows to define two different views: one that shows the data in the spinner itself and one that shows the data in the drop down list when the spinner is pressed.

WrapperListAdapter: List adapter that wraps another list adapter. The wrapped adapter can be retrieved by calling getWrappedAdapter().

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 63: Android Adapters, An Introduction

Spinner down arrow stretching?

.. Styling the inner and outer views of a Spinner individually.

I was working with a Spinner with a lot of rows fetched from a database, and wanted to put a bit of padding around each item to make it easier for the user to select them.

So I went into my res\layout\spinner_view_row.xml (which controls how the Spinner rows display) and added this:

android:padding="5dip"

Then, when I went and re-ran my app, what used to look like this:

.. now looks like this:

.. Ooops.

Looks like a condom doesn't it. Not what I was trying to achieve, really. If I made the padding large enough, it will also look like that before I've even selected anything.

Not what I wanted at all.

But I do want that padding around each item in my Spinner, otherwise my users will have too much trouble choosing items from my latest super-dooper, take-the-world-by-storm, #1 in the world market app, and it might not stay #1 for long at all.

Luckily, the answer is really, really simple.

You might recogise the below as the piece of code that binds a cursor from the database (containing all the items we want to display), to the xml view spinner_view_row, located at res\layout\spinner_view_row.xml (this is the xml file

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 64: Android Adapters, An Introduction

in which we put the extra padding, above).

final SimpleCursorAdapter ingredientAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, ingredientsCursor, from, to); ingredientAdapter.setDropDownViewResource(R.layout.spinner_view_row);

spnIngredients.setAdapter(ingredientAdapter);

All we need to do to avoid the stretchy condom spinner arrow is to define another xml view in res\layout\ and call it something like spinner_view_closed, then paste into it the same code that you have in spinner_view_row. Simply then customise this xml to have less padding, or a smaller text size for instance, then replace the reference to

simple_spinner_itemwith a reference to this new xml file, like this:

final SimpleCursorAdapter ingredientAdapter = new SimpleCursorAdapter(this, R.layout.spinner_view_row_closed, ingredientsCursor, from, to); ingredientAdapter.setDropDownViewResource(R.layout.spinner_view_row);

spnIngredients.setAdapter(ingredientAdapter);

.. and your new Spinner will look like this when open:

.. and this when closed.

Tuesday, January 12, 2010

Layout Tricks: Creating Reusable UI Components A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 65: Android Adapters, An Introduction

The Android platform offers a wide variety of UI widgets, small visual construction blocks that you can glue together to present users with complex and useful interfaces. However applications often need higher-level visual components. To meet that need, and to do so efficiently, you can combine multiple standard widgets into a single, reusable component.

For example, you could create a reusable component that contains a progress bar and a cancel button, a panel containing two buttons (positive and negative actions), a panel with an icon, a title and a description, and so on. You can create UI components easily by writing a custom View, but you can do it even more easily using only XML.

In Android XML layout files, each tag is mapped to an actual class instance (the class is always a subclass of View, The UI toolkit lets you also use three special tags that are not mapped to a View instance: <requestFocus />, <merge /> and <include />. This article shows how to use <include /> to create pure XML visual components.

The <include /> element does exactly what its name suggests; it includes another XML layout. Using this tag is straightforward as shown in the following example:

<com.android.launcher.Workspaceandroid:id="@+id/workspace"android:layout_width="fill_parent"android:layout_height="fill_parent"

launcher:defaultScreen="1">

<include android:id="@+id/cell1" layout="@layout/workspace_screen" /><include android:id="@+id/cell2" layout="@layout/workspace_screen" /><include android:id="@+id/cell3" layout="@layout/workspace_screen" />

</com.android.launcher.Workspace>

In the <include /> only the layout attribute is required. This attribute, without the android namespace prefix, is a reference to the layout file you wish to include. In this example, the same layout is included three times in a row. This tag also lets you override a few attributes of the included layout. The above example shows that you can use android:id to specify the id of the root view of the included layout; it will also override the id of the included layout if one is defined. Similarly, you can override all the layout parameters. This means that any android:layout_* attribute can be used with the <include /> tag. Here is an example:

<include android:layout_width="fill_parent" layout="@layout/image_holder" /><include android:layout_width="256dip" layout="@layout/image_holder" />

Thursday, January 14, 2010

Including layouts: a working example

Here's a working example of including one layout inside another.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 66: Android Adapters, An Introduction

Let me know if you have any issues or questions.This works with, and probably requires, a AVD version of 2.1 or thereabouts.

contents of droidTest1.java:

package androidforbeginners.droidTest1;

import android.app.Activity;import android.os.Bundle;

public class droidTest1 extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}}

contents of 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"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="combining layouts"/>

<include android:id="@+id/cell1" layout="@layout/layout2" /><include android:id="@+id/cell2" layout="@layout/layout3" />

</LinearLayout>

Contents of layout2.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"

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 67: Android Adapters, An Introduction

android:layout_height="100px"android:background="#0033cc"><TextViewandroid:layout_width="fill_parent"android:layout_height="40px"android:text="layout2"/><CheckBoxandroid:layout_width="fill_parent"android:layout_height="40px"/></LinearLayout>

Contents of layout3.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="100px"android:background="#0066cc"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="layout3"/><CheckBoxandroid:layout_width="fill_parent"android:layout_height="wrap_content"/></LinearLayout>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 68: Android Adapters, An Introduction

Output:

You could also include multiple occurrences of the one layout in your main.xml like this if you wanted:

contents of main.xml (revised):

<?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"><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="combining layouts"/>

<include android:id="@+id/cell1" layout="@layout/layout2" /><include android:id="@+id/cell2" layout="@layout/layout2" /><include android:id="@+id/cell3" layout="@layout/layout2" /><include android:id="@+id/cell4" layout="@layout/layout2" />

</LinearLayout>

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 69: Android Adapters, An Introduction

Although if you do this, I can't see a way to reference individual repeating items.

I think include is more including a single layout across multiple Activities.

Let me know in the comments if you know a way.

uesday, December 22, 2009

The difference between @+id and @android:id

Sometimes you see references in your layout files like:

<listview id="@+id/android:list">

and

<listview id="@android:id/list">

What's the difference?

.. I'm glad you asked ☺

@+id/foo means you are creating an id named foo in the namespace of your application.You can refer to it using @id/foo.@android:id/foo means you are referring to an id defined in the android namespace.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 70: Android Adapters, An Introduction

The '+' means to create the symbol if it doesn't already exist. You don't need it (and shouldn't use it) when referencing android: symbols, because those are already defined for you by the platform and you can't make your own in that namespace anyway.

This namespace is the namespace of the framework.for example, you need to use @android:id/list because this the id the framework expects to find.. (the framework knows only about the ids in the android namespace.)

Monday, January 18, 2010

Psst..Remember that your layout files must have lowercase names..

Remember that your layout files must have lowercase names, or they won't show up in your autoComplete list of options after 'R.layout' in Eclipse when you try this :

setContentView(R.layout.test_db);

The file won't actually show up as having any errors in your package explorer (on the right by default in the IDE), but if you look down in the console (by default down the bottom), you'll see this:

Invalid file name: must contain only [a-z0-9_.]

You might see an error on your project name, but with all the folders and files it can be hard to track down the cause.

When you try to run your application you will see:

'Your project contains error(s) please fix them before running your application'

.. and it won't be happy until you delete the offending file, even if you're not actively referencing it in your code.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 71: Android Adapters, An Introduction

How to create Status Bar Notifications

A status bar notification is used to notify the user of a system event, like an sms being received or a new device being detected, without interrupting the user from whatever other task they might be doing with their phone.

The status bar area is located at the top of the screen and the user can pull this area to expand it, and show a history of notifications.

If a Notification has been setup to include an enclosed Intent, selecting that particular notification in this expanded view can fire the Intent, taking the user to an Activity screen of the related application, or do any of the many other things that Intents can do.

You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Page 72: Android Adapters, An Introduction

A background Service should never launch an Activity on its own in order to receive user interaction. The Service should instead create a status bar notification that will launch the Activity when selected by the user.

A status bar notification should be used for any case in which a background Service needs to alert the user about an event.

Here is a simple method that creates and displays a notification when passed a string msg :

public void displayNotification(String msg){NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);Notification notification = new Notification(R.drawable.icon, msg, System.currentTimeMillis());

// The PendingIntent will launch activity if the user selects this notificationPendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, ExpandNotification.class), 0);

notification.setLatestEventInfo(this, "Title here", ".. And here's some more details..", contentIntent);

manager.notify(NOTIFICATION_ID, notification);

}

.. Which you can call simply like this:

displayNotification("Hi, I'm a Statusbar Notification.."

A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi