final int resourceStart = 17301504; final int resourceEnd = 17301655; final int ResourceLength = resourceEnd - resourceStart + 1;
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
private GridView.OnItemClickListener gridviewOnItemClickListener = new GridView.OnItemClickListener(){
@Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub String strResource = arg0.getAdapter().getItem(arg2).toString() + " " + Resources.getSystem().getResourceName(arg2+resourceStart); Toast.makeText(AndroidGridView2.this, strResource, Toast.LENGTH_LONG).show(); } };
public class ImageAdapter extends BaseAdapter { private Context mContext;
public ImageAdapter(Context c) { mContext = c; initResourceID(); }
public int getCount() { return mThumbIds.length; }
public Object getItem(int position) { return mThumbIds[position]; }
public long getItemId(int position) { return position; }
// create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(50, 50)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; }
private int[] mThumbIds = new int[ResourceLength]; private void initResourceID(){ for ( int i = 0; i < ResourceLength; i++) { mThumbIds[i] = i + resourceStart; } } } }
The Hierarchy Viewer application allows you to debug and optimize your user interface. It provides a visual representation of the layout's View hierarchy (the Layout View) and a magnified inspector of the display (the Pixel Perfect View).
To get the Hierarchy Viewer started:
1. Connect your device or launch an emulator. 2. From a terminal, launch hierarchyviewer from your SDK /tools directory. 3. In the window that opens, you'll see a list of Devices. When a device is selected, a list of currently active Windows is displayed on the right. The "focused window" is the window currently in the foreground, and also the default window loaded if you do not select another. 4. Select the window that you'd like to inspect and click Load View Hierarchy. The Layout View will be loaded. You can then load the Pixel Perfect View by clicking the second icon at the bottom-left of the window.
If you've navigated to a different window on the device, press Refresh Windows to refresh the list of available windows on the right.
GridView shows items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This exercise show how to implement a GridView to display drawable in /res.
- Create a Android Application, AndroidGridView2 (It's my first time to use Android SDK r3 for Android 2.0). Target Android 2.0 (not necessary).
- Copy some picture files (or download from the file on the end of this text) into the folder /res/drawable-ldpi/ (for Android 2.0) or /res/drawable/ for former version, named drawing_01~14.png
public class AndroidGridView2 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
private GridView.OnItemClickListener gridviewOnItemClickListener = new GridView.OnItemClickListener(){
@Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(AndroidGridView2.this, arg0.getAdapter().getItem(arg2).toString(), Toast.LENGTH_LONG).show(); }
};
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 mThumbIds[position]; }
public long getItemId(int position) { return position; }
// create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes 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; }
-------------------------------------------------------------------- Little bit advice: - Set a break point inside getView(), you can know more on the operation of getView, such as when it will be called, and when go to initialize attributes, or load the previous convertView.
- Modify onItemClick() to check the value of arg0, arg1, arg2 & arg3.
In my code, the object ID of the clicked item of the GridView will be displayed on the Toast, in decimal. It's match with the ID of the item in the file R.java, in hexdecimal.
- Try the Tool, hierarchyviewer, it can give you a hierarchy viewer of the current view. --------------------------------------------------------------------
If you have already installed Android 1.6 SDK and Eclipse, it's very easy to upgrade to Android SDK Tools, Revision 3. The Android SDK and AVD Manager tool is included in Android 1.6 and later SDK packages.
Click Window on top menu of Eclipse, click Android SDK and AVD Manager.
Select Avaolable Package, wait a moments, the available Sources, Packages and Archieves will be shown on the right. Select the components you want.
Accept All
Wait download and install.
After downloaded and installed, you will be asked to restart Eclipse.
After Eclipse restart, you will ne asked to update ADT.
Click Help on top of Eclipse, click Install New Software...
Select the site https://dl-ssl.google.com/android/eclipse/
It should be already in your list if you have installed Android SDK before. Wait a moment the available ADT will be appear. Select available ADT and click Next
Next and Accept the terms, and click Finish. And wait installation of the the new ADT.
Android 2.0 is a major platform release deployable to Android-powered handsets starting in November 2009. The release includes new features for users and developers, as well as changes in the Android framework API.
Now, I have another approach using in Eclipse, Emulator and DDMS. May be it's more easy, at least no need to remember the text commands.
Create a new AVD in Eclipse:
- Start Eclipse, click Window on the top menu, and click Android SDK and AVD Manager. - New a AVD
- Name your new AVD, select Target, type 1000M in SD Card and select skin. Click Create. note: SD Card must be either a file path or a size such as 128K 0r 64M. type 1000M now to create a SD Card of 1G. - Select and Start the new AVD.
After the Emulator started, you can close the AVD Manager.
Create folder in SDCard
I can't find any File Manager in Android Emulator. Fortunately, Android Emulator provide a DevTools with Terminal, so you can create a folder using Linux command inside Android Emulator.
- Click the ARROW on the screen to display the available application.
- Click DevTools.
- Scroll down to start Terminal Emulator
- It's the same a terminal in Linux, you can ls to view the current files and folders in your $home.
- Now change into sdcard and create a folder, say pictures. $cd sdcard $mkdir pictures
It's the only two line of command in this approach.
Copy files from your host system into Android SDCard
- With the Emulator is running. Now go back to Eclipse, switch to DDMS Perspective
Click the arrow on the menu bar and select DDMS
or
Click Window > Open Perspective > others > to select DDMS
- Select the device in the window on the left, eg. emulator-5554. (Without select the device, you will fail in copying files into.)
- In DDMS, select File Explorer tag in the window on the right. Expend sdcard folder. Now, you can see the pictures folder in the tree. And also, you can see the Permissions of the folder.
- Select the pictures folder, and click Push a file onto the device .
- Browse to and select the files from your host, to push onto the Android Emulator.
- Further expend the folder pictures, you can see the new file here.
But...actually, I can't make my Emulator to have any sound using this method. May be there are some setting missed in my Emulator. (If you know why, please leave me a comment to let me know, thx.)
Alternatively, I use a mp3 file in sdcard as Notification sound.
A status bar notification adds an icon to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window.
After Notification generated, a selected notification icon and Ticket will be displayed on the status bar.
User can reveal the Notifications window by pulling down the status bar (or selecting Notifications from the Home options menu), to view the Title and Content.
Notification can be generated inside Service or Activity. This exercise show the basic steps to generate a Notification in Activity.
The most important class is NotificationManager and Notification.
In the exercise: android.R.drawable.btn_star_big_on is a drawable icon in Android system resource, you can assign any drawable icon. when is when the notification should be generated, System.currentTimeMillis() = NOW. NOTIFICATION_ID is a number which is unique in your application. contentIntent is the expected intent to handle the notification. It's the own activity in this exercise.
The generated Notification can be cleared by: NotificationManager.cancel(NOTIFICATION_ID);
Modify main.xml to have two Buttons to generate and clear the Notification
public class AndroidNotification extends Activity {
NotificationManager myNotificationManager; private static final int NOTIFICATION_ID = 1;
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
Normally, ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list".
In some case if the list is empty, the screen will become nothing. If you want to prompt the user if the list is empty, @android:id/list and @android:id/empty can be used.
Create a new AndroidEmptyListActivity extends ListActivity.
In the article Layout Animation, list_layout_controller is included in layout, main.xml. In the last article ListView and ListActivity, ListView is implemented as ListActivity, without XML file for layout. How can apply the LayoutAnimationController.
In this article, the same visual effect of Layout Animation will be applied on ListView and ListActivity.
A ListView is a View that shows items in a vertically scrolling list. The items are acquired from a ListAdapter.
In this exercise, I will show how to implement a ListView using ListActivity. The main activity (AndroidListView) call the ListActivity(AndroidListActivity) by startActivityForResult. AndroidListActivity have a ListView only, the selected item will be passed back to AndroidListView by means of Bundle.
_ Create a new Android Application named AndroidListView
- Modify main.xml to have a Button to start the ListActivity with ListView, and have a TextView to show the result from ListActivity.
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
private Button.OnClickListener SelectCountryButtonOnClickListener = new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(AndroidListView.this, AndroidListActivity.class);
startActivityForResult(intent, 0); } };
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode==0) { switch (resultCode) { case RESULT_OK: MyCountry.setText(data.getStringExtra("country")); break; case RESULT_CANCELED: break;
}
} }
}
- Create AndroidListActivity extends ListActivity
Right click com.exercise.AndroidListView, the package In the Project Windows on the left. Select New > Class >
Click Browser beside Superclass, select ListActivity. (May be you have to clear the content inside "Choose a type" box to make it appear in the "Matching items" list.
Notice that we don't need to load a layout (at least, not in this case, because we're using the whole screen for our list). Instead, we just call setListAdapter() (which automatically adds a ListView to the ListActivity), and provide it with an ArrayAdapter that binds a simple_list_item_1 layout item to each entry in the COUNTRIES array (added next). The next line of code adds a text filter to the ListView, so that when the user begins typing, the list will filter the entire view to display only the items that match the entry.
- Modify AndroidMainfest.xml to include the AndroidListActivity.
Layout Animation can be used to add visual effects on any controls derived from ViewGroup, such as ListView. ListView is a view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.
In this article, I will have a example to show how to implement a simple Layout Animation.
Create a Android Application named AndroidLayoutAnimation.
- Create a new folder named /anim under /res
- Create two xml file under /res/anim to handle the animation list_layout_controller.xml
- Modify AndroidLayoutAnimation.java to setContentView() using listlayout.xml, and SetupListView(). In order to show the effect, a button is used to restart the animation.
public class AndroidLayoutAnimation extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
loadScreen(); }
private Button.OnClickListener MyRestartButtonOnClickListener = new Button.OnClickListener(){
@Override public void onClick(View v) { // TODO Auto-generated method stub loadScreen(); } };
private void SetupListView() { String[] listItems = new String[] { "Hello!", "It's a Demo to use Layout Animation", "Is it Great?", "android-er.blogspot.com" };
ArrayAdapter<String> listItemAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, listItems);
In the article Simulate Animation, using Runnable Thread, I described how to simulate animation using Runnable Thread. For sure, it's not a good practice. In this article I show how to implement animation using animation-list and AnimationDrawable.
The animation can be started and stopped by the two button, Start and Stop.
- Save the four graphics, used to form the animation of a rotating arrow, in the /res/drawable/ folder.
- Create a file named arrow_animation.xml in /res/drawable
It's a Twitter Client post updated status using Twitter API.
There are three EditText in the application, for user name, password (hiden by password dots) and updated status. Submit to Twitter by pressing of the Submit button. If successful, a Toast with "OK" will be shown, otherwise "ERROR" will be shown.
- Before start; base64 is needed in the application, refer to the article Use base64 in Android to download and include it in the Build Path of the project.
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
------------------------ Actually, I can't find anywhere to download sun.misc.BASE64Encoder. Somebody advise that it can be found in /jre/lib/rt.jar. I tried to add it to my build path, but my machine hang-up in build my project. So...I give-up sun.misc.BASE64Encoder finally. ------------------------
Alternatively, there is a package, Commons Codec, from apache.org.
To use the Commons Codec, you have to download it from http://commons.apache.org/codec/download_codec.cgi, and save it to your local driver. The current version 1.4 that requires a minimum of JDK 1.4.
In Eclipse, right click your project > Build Path > Add External Archives >, browse to select the downloaded and extracted JAR.
The syntex to encode a input to base54 is:
import org.apache.commons.codec.binary.Base64;
String outputString = new String(Base64.encodeBase64(inputString.getBytes()));
Both inputString and outputString are in type String.