'분류 전체보기'에 해당되는 글 417건

  1. 2010.02.04 자료 보관할 내용. 1
  2. 2010.02.03 안드로이드 위젯에서 Activity 호출하기. 17
  3. 2010.02.02 How to make a simple Android widget 5
  4. 2010.01.29 공개 채팅 서버 openfire 설치 구동
  5. 2010.01.28 Using Google Maps in Android 63
  6. 2010.01.22 A Visual Guide to Android GUI Widgets
  7. 2010.01.21 안드로이드 에뮬레이터에 가상의 SD카드 마운트시키기
  8. 2010.01.20 Web View 샘플구현 8
  9. 2010.01.19 Using java.net.URL for input stream access 8
  10. 2010.01.19 안드로이드 ListActivity 링크소스 10
2010. 2. 4. 18:41

자료 보관할 내용.




 * Copyright (C) 2009 The Android Open Source Project 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */ 
 
package com.example.android.wiktionary; 
 
import com.example.android.wiktionary.SimpleWikiHelper.ApiException; 
import com.example.android.wiktionary.SimpleWikiHelper.ParseException; 
 
import android.app.PendingIntent; 
import android.app.Service; 
import android.appwidget.AppWidgetManager; 
import android.appwidget.AppWidgetProvider; 
import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.res.Resources; 
import android.net.Uri; 
import android.os.IBinder; 
import android.text.format.Time; 
import android.util.Log; 
import android.widget.RemoteViews; 
 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
 
/** 
 * Define a simple widget that shows the Wiktionary "Word of the day." To build 
 * an update we spawn a background {@link Service} to perform the API queries. 
 */ 
public class WordWidget extends AppWidgetProvider { 
    /** 
     * Regular expression that splits "Word of the day" entry into word 
     * name, word type, and the first description bullet point. 
     */ 
    public static final String WOTD_PATTERN = 
        "(?s)\\{\\{wotd\\|(.+?)\\|(.+?)\\|([^#\\|]+).*?\\}\\}"; 
 
    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
        Log.d("WordWidget.UpdateService", "onUpdate()"); 
        // To prevent any ANR timeouts, we perform the update in a service 
        context.startService(new Intent(context, UpdateService.class)); 
    } 
     
    public static class UpdateService extends Service { 
        @Override 
        public void onStart(Intent intent, int startId) { 
            Log.d("WordWidget.UpdateService", "onStart()"); 
 
            // Build the widget update for today 
            RemoteViews updateViews = buildUpdate(this); 
            Log.d("WordWidget.UpdateService", "update built"); 
             
            // Push update for this widget to the home screen 
            ComponentName thisWidget = new ComponentName(this, WordWidget.class); 
            AppWidgetManager manager = AppWidgetManager.getInstance(this); 
            manager.updateAppWidget(thisWidget, updateViews); 
            Log.d("WordWidget.UpdateService", "widget updated"); 
        } 
 
        @Override 
        public IBinder onBind(Intent intent) { 
            return null; 
        } 
         
        /** 
         * Build a widget update to show the current Wiktionary 
         * "Word of the day." Will block until the online API returns. 
         */ 
        public RemoteViews buildUpdate(Context context) { 
            // Pick out month names from resources 
            Resources res = context.getResources(); 
            String[] monthNames = res.getStringArray(R.array.month_names); 
             
            // Find current month and day 
            Time today = new Time(); 
            today.setToNow(); 
 
            // Build the page title for today, such as "March 21" 
            String pageName = res.getString(R.string.template_wotd_title, 
                    monthNames[today.month], today.monthDay); 
            String pageContent = null; 
             
            try { 
                // Try querying the Wiktionary API for today's word 
                SimpleWikiHelper.prepareUserAgent(context); 
                pageContent = SimpleWikiHelper.getPageContent(pageName, false); 
            } catch (ApiException e) { 
                Log.e("WordWidget", "Couldn't contact API", e); 
            } catch (ParseException e) { 
                Log.e("WordWidget", "Couldn't parse API response", e); 
            } 
             
            RemoteViews views = null; 
            Matcher matcher = null; 
             
                Prefs prefs = new Prefs(this); 
            if (pageContent == null) { 
                // could not get content, use cache 
                // could be null 
                pageContent = prefs.getPageContent(); 
            } 
             
            if (pageContent != null) { 
                // we have page content 
                // is it valid? 
                matcher = Pattern.compile(WOTD_PATTERN).matcher(pageContent); 
            } 
            if (matcher != null && matcher.find()) { 
                // valid content, cache it  
                // ensure that latest valid content is 
                // always cached in case of failures 
                prefs.setPageContent(pageContent); 
 
                // Build an update that holds the updated widget contents 
                views = new RemoteViews(context.getPackageName(), R.layout.widget_word); 
                 
                String wordTitle = matcher.group(1); 
                views.setTextViewText(R.id.word_title, wordTitle); 
                views.setTextViewText(R.id.word_type, matcher.group(2)); 
                views.setTextViewText(R.id.definition, matcher.group(3).trim()); 
                 
                // When user clicks on widget, launch to Wiktionary definition page 
                String definePage = String.format("%s://%s/%s", ExtendedWikiHelper.WIKI_AUTHORITY, 
                        ExtendedWikiHelper.WIKI_LOOKUP_HOST, wordTitle); 
                Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(definePage)); 
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 
                        0 /* no requestCode */, defineIntent, 0 /* no flags */); 
                views.setOnClickPendingIntent(R.id.widget, pendingIntent); 
                 
            } else { 
                // Didn't find word of day, so show error message 
                views = new RemoteViews(context.getPackageName(), R.layout.widget_message); 
                views.setTextViewText(R.id.message, context.getString(R.string.widget_error)); 
            } 
            return views; 
        } 
    } 
} 

2010. 2. 3. 18:13

안드로이드 위젯에서 Activity 호출하기.




1. 호출 받을 Activity의 xml 파일 만들기. layout/appwidgetmain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_height="200dp"
    android:background="@drawable/background"
    android:layout_width="160dp"
    android:orientation="horizontal">
    <Button
     android:text="@+id/Button01"
     android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content">
    </Button>
    <TextView
        android:id="@+id/widget_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:textColor="@android:color/black"
        android:text="17:12:34 PM"
        android:textSize="8pt"
    />
</LinearLayout>

호출 받을 Activity만들기
package com.sh.watchwidget;
import android.app.Activity;
import android.os.Bundle;
public class MyActvity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
 
     // TODO Auto-generated method stub
 }
}


위젯의 배경 이미지 만들기 /res/drawable/background.png

위젯의 레이아웃 만들기 . layout/appwidgetmain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_height="200dp"
    android:background="@drawable/background"
    android:layout_width="160dp"
    android:orientation="horizontal">
    <Button
     android:text="@+id/Button01"
     android:id="@+id/Button01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content">
    </Button>
    <TextView
        android:id="@+id/widget_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:textColor="@android:color/black"
        android:text="17:12:34 PM"
        android:textSize="8pt"
    />
</LinearLayout>


AppWidgetProvider를 상속 받은 위젯 메인 페이지 만들기.
package com.sh.watchwidget;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
public class WatchWidget extends AppWidgetProvider
{
    @Override
    public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds )
    {
        RemoteViews remoteViews;
        ComponentName watchWidget;
        DateFormat format = SimpleDateFormat.getTimeInstance( SimpleDateFormat.MEDIUM, Locale.getDefault() );
        Intent intent = new Intent();
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setComponent(new ComponentName("com.sh.watchwidget", "com.sh.watchwidget.MyActvity"));
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        remoteViews = new RemoteViews( context.getPackageName(), R.layout.appwidgetmain );
        watchWidget = new ComponentName( context, WatchWidget.class );
        remoteViews.setTextViewText( R.id.widget_textview, "Time = " + format.format( new Date()));
        remoteViews.setOnClickPendingIntent(R.id.Button01, pendingIntent);
        appWidgetManager.updateAppWidget( watchWidget, remoteViews );
       
       
    }
}

appwidget-provider xml 파일 만들기
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:initialLayout="@layout/appwidgetmain"
    android:updatePeriodMillis="1000" 
    android:minHeight="144dp"/>

AndroidManifest.xml 파일에 application 추가하기

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sh.watchwidget"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
        <receiver android:name=".WatchWidget" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/watch_widget_provider" />
        </receiver>
    <activity android:name="MyActvity"></activity>
</application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

결과 화면
 

소스를 보면 간단하지만 2일동안 삽질하여 만들 소스입니다.


아래는 아카이브 파일입니다.
2010. 2. 2. 09:21

How to make a simple Android widget





Yesterday I made my first Android widget. A very simple widget, just to try it out. It can show the time. No more, no less. I will here show you how to get started on widgets. I’ll start from scratch, so you actually don’t need any knowledge on Android development. Well, of course you need to have the SDK, and Eclipse installed and ready.

I used the 1.5 SDK, but it will probably work on newer SDK’s too.

I will show you how to do it in 6 easy steps.

 

1. Create a new Android project
Fire up Eclipse, and click File -> New -> Android project
Skærmbillede 2009-11-07 kl. 14.26.27
Type in a name for you project, eg. WatchWidget. Select the target, 1.5 in my case. I guess that there could be differences, so if you are not experienced in Android development, I suggest that you use 1.5 too.

Then we need an application name, which is the name that will show up on your phone. And last but not least, a package name.

Uncheck “Create activity”, as we don’t want any activities in this sample.

Click Finish to create the project. Now you have a structure that looks like this:

WatchWidget structure

 

2. Create the Java class
Right-click com.kasperholtze.watchwidget (or whatever you used for package name), and select New -> Class:

Create WatchWidget class

Give the class a name, i.e. WatchWidget. Then we need to extend the AppWidgetProvider, so type in android.appwidget.AppWidgetProvider as superclass, or browse for it.

Click Finish, and Eclipse will generate the following code:

package com.kasperholtze.watchwidget;

import android.appwidget.AppWidgetProvider;

public class WatchWidget extends AppWidgetProvider {

}

 

3. Create the Java code
Now it’s time to create our Java code, for updating the widget. Type in the following code:

package com.kasperholtze.watchwidget;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import com.kasperholtze.watchwidget.R;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.widget.RemoteViews;

public class WatchWidget extends AppWidgetProvider
{
    @Override
    public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds )
    {
        RemoteViews remoteViews;
        ComponentName watchWidget;
        DateFormat format = SimpleDateFormat.getTimeInstance( SimpleDateFormat.MEDIUM, Locale.getDefault() );

        remoteViews = new RemoteViews( context.getPackageName(), R.layout.main );
        watchWidget = new ComponentName( context, WatchWidget.class );
        remoteViews.setTextViewText( R.id.widget_textview, "Time = " + format.format( new Date()));
        appWidgetManager.updateAppWidget( watchWidget, remoteViews );
    }
}

The only method we use in this class, is onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ), which we override from the AppWidgetProvider class.

First we create three objects. remoteViews, watchWidget and format. remoteViews is a reference to the main view, which we will create in a moment. watchWidget is a reference to our class, and format is the date format used to show the time.

Then we initialize the remoteViews and watchWidget. You will get an error one the line remoteViews.setTextViewText(), which is where we actually update the text on our widget, stating that R.id is not found, but that’s all right for now. We will create that one in a moment too.

appWidgetManager.updateAppWidget sets the RemoteViews that should be used for our widget.

 

4. Edit the view for our widget, main.xml
Using the UI designer takes some trying, testing and failing. If you have not tried this yet, you should try playing around with it. It takes some time to get the feeling of it.

My main.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_height="200dp"
    android:background="@drawable/background"
    android:layout_width="160dp"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/widget_textview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical|center_horizontal"
        android:textColor="@android:color/black"
        android:text="17:12:34 PM"
        android:textSize="8pt"
    />
</LinearLayout>

It contains a LinearLayout with a TextView inside. The important thing is the id of out TextView, which we used earlier in the WatchWidget class.
I used a standard widget background, which you can download at http://developer.android.com/guide/practices/ui_guidelines/widget_design.html. You can also grab it here:

WatchWidget background

Save it in the project, at res/drawable/background.png

 

5. Edit AndroidManifest.xml
The next thing is to edit the AndroidManifest.xml, which defines the application. We need to add an intent-filter, meta-data that defines which xml file we use for defining the widget provider, and name and other details of the application.

Here it goes…

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kasperholtze.watchwidget"
    android:versionCode="1"
    android:versionName="1.0">

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <receiver android:name=".WatchWidget" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/watch_widget_provider" />
        </receiver>

    </application>
   
    <uses-sdk android:minSdkVersion="3" />

</manifest>

 

6. Create widget provider
The last thing we have to do, before the application is ready to run, is to create a XML file, defining the widget provider. Create a new folder under res, called xml, and save the file as res/xml/watch_widget_provider.xml.

<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:initialLayout="@layout/main"
    android:updatePeriodMillis="1000"
    android:minHeight="144dp"/>

Here we set the minimum size that the widget needs to be added to a home screen. And then we set the updatePeriodMillis. updatePeriodMillis defines how often we wish to call the onUpdate method that we created earlier in the Java class.

That’s it! Connect your phone, or fire up a virtual device, and try it out

2010. 1. 29. 17:40

공개 채팅 서버 openfire 설치 구동





XMPP(eXtensible Messaging and Presence Protocol) 프로토콜 기반의 공개 채팅서버인 OpenFire를 로컬 경로에 설치하고 테스트 해 보았습니다.

지원하는 플랫폼은 Windows/Linux/Mac 입니다.


사용자 삽입 이미지

다운로드 URL : http://www.igniterealtime.org/projects/openfire/index.jsp
설치 가이드 : http://www.igniterealtime.org/builds/openfire/docs/latest/documentation/install-guide.html


저는 Windows용 무설치 버전을 받아 C:\openfire 경로에 압축을 해제 하였습니다.
(* 바탕화면에 압축 해제 후 실행시 한글 경로를 찾지 못하는 현상이 있는 듯 합니다.)




압축 해제 후 다음과 같이 실행합니다.

openfire-service.exe /install  (설치)
openfire-service.exe /start  (서버 시작)

openfire.exe  (실행)



사용자 삽입 이미지


위와 같은 Openfire 창이 뜨면 Launch Admin 버튼으로 초기 세팅을 진행해야 합니다.



서버정보, DB계정등을 입력해야 Openfire가 정상적으로 구동됩니다.
MySQL 이외의 DB서버를 사용한다면 DB서버에 따라 jdbc 라이브러리를 /lib 디렉토리에 위치시켜 놓고 서버를 재시작 합니다.


  • openfire-service /install -- installs the service.
  • openfire-service /uninstall -- uninstalls the service.
  • openfire-service /start -- starts the service
  • openfire-service /stop -- stops the service.




  • 모든 설치과정이 끝나면, 클라이언트를 통해 메신저 서버에 접속 할 수 있습니다.

    Spark 또는 SparkWeb을 통해 접속 해 봅니다.


    사용자 삽입 이미지


    정상적으로 동작합니다.


    GPL 이기 때문에 소스를 SVN에서 받아 수정 해 사용하면 될 듯 싶습니다.





    --- 2009.04.07. 추가 ---

    저도 위와 같이 서버와 클라이언트를 설치하여 사용만 해 봤을 뿐이라 많은 정보를 드리지 못해서 죄송합니다.
    국내나 해외에도 해당 소스를 수정하여 진행하는 작업에 대한 정보도 많지 않았습니다.

    혹시 오픈파이어나 Spark를 가지고 진행하는 프로젝트를 하고 계시다면 또는 정보를 정리하고 계신다면 트랙백 걸어주시거나 정보 링크를 댓글로 알려주시면 많은 분들이 도움이 될것 같습니다.
    2010. 1. 28. 16:06

    Using Google Maps in Android





    Creating the Project

    Using Eclipse, create a new Android project and name GoogleMaps as shown in Figure 1.


    Figure 1 Creating a new Android project using Eclipse

    Obtaining a Maps API key

    Beginning with the Android SDK release v1.0, you need to apply for a free Google Maps API key before you can integrate Google Maps into your Android application. To apply for a key, you need to follow the series of steps outlined below. You can also refer to Google's detailed documentation on the process at http://code.google.com/android/toolbox/apis/mapkey.html.

    First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of "C:\Documents and Settings\<username>\Local Settings\Application Data\Android". The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.

    For simplicity, copy this file (debug.keystore) to a folder in C:\ (for example, create a folder called "C:\Android").

    Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the "C:\Program Files\Java\<JDK_version_number>\bin" folder.

    Issue the following command (see also Figure 2) to extract the MD5 fingerprint.

    keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass
     android -keypass android

    Copy the MD5 certificate fingerprint and navigate your web browser to: http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page to complete the application and obtain the Google Maps key.


    Figure 2 Obtaining the MD5 fingerprint of the debug keystore

    To use the Google Maps in your Android application, you need to modify your AndroidManifest.xml file by adding the <uses-library> element together with the INTERNET permission:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="net.learn2develop.GoogleMaps"
          android:versionCode="1"
          android:versionName="1.0.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name">
     
        <uses-library android:name="com.google.android.maps" />  
     
            <activity android:name=".MapsActivity"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
     
        <uses-permission android:name="android.permission.INTERNET" />
     
    </manifest>
    </xml>

    Displaying the Map

    To display the Google Maps in your Android application, modify the main.xml file located in the res/layout folder. You shall use the <com.google.android.maps.MapView> element to display the Google Maps in your activity. In addition, let's use the <RelativeLayout> element to position the map within the activity:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
     
        <com.google.android.maps.MapView 
            android:id="@+id/mapView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:enabled="true"
            android:clickable="true"
            android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
            />
     
    </RelativeLayout>

    Notice from above that I have used the Google Maps key that I obtained earlier and put it into the apiKey attribute.

    In the MapsActivity.java file, modify the class to extend from the MapActivity class, instead of the normal Activity class:

    package net.learn2develop.GoogleMaps;
     
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapView;
    import android.os.Bundle;
     
    public class MapsActivity extends MapActivity 
    {    
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            return false;
        }
    }

    Observe that if your class extends the MapActivity class, you need to override the isRouteDisplayed() method. You can simply do so by setting the method to return false.

    That's it! That's all you need to do to display the Google Maps in your application. Press F11 in Eclipse to deploy the application onto an Android emulator. Figure 3 shows the Google map in all its glory.


    Figure 3 Google Maps in your application

    At this juncture, take note of a few troubleshooting details. If your program does not run (i.e. it crashes), then it is likely you forgot to put the following statement in your AndroidManifest.xml file:

        <uses-library android:name="com.google.android.maps" />

    If your application manages to load but you cannot see the map (all you see is a grid), then it is very likely you do not have a valid Map key, or that you did not specify the INTERNET permission:

        <uses-permission android:name="android.permission.INTERNET" />

    Displaying the Zoom View

    The previous section showed how you can display the Google Maps in your Android device. You can drag the map to any desired location and it will be updated on the fly. However, observe that there is no way to zoom in or out from a particular location. Thus, in this section, you will learn how you can let users zoom into or out of the map.

    First, add a <LinearLayout> element to the main.xml file as shown below:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent">
     
        <com.google.android.maps.MapView 
            android:id="@+id/mapView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:enabled="true"
            android:clickable="true"
            android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
            />
     
        <LinearLayout android:id="@+id/zoom" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:layout_alignParentBottom="true" 
            android:layout_centerHorizontal="true" 
            /> 
     
    </RelativeLayout>

    You will use the <LinearLayout> element to hold the two zoom controls in Google Maps (you will see this shortly).

    In the MapsActivity.java file, add the following imports:

    import com.google.android.maps.MapView.LayoutParams;  
    import android.view.View;
    import android.widget.LinearLayout;

    and add the following code after the line setContentView(R.layout.main);

            mapView = (MapView) findViewById(R.id.mapView);
            LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
            View zoomView = mapView.getZoomControls(); 
     
            zoomLayout.addView(zoomView, 
                new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT)); 
            mapView.displayZoomControls(true);

    The complete MapsActivity.java file is given below:

    package net.learn2develop.GoogleMaps;
     
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapView;
    import com.google.android.maps.MapView.LayoutParams;  
     
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
     
    public class MapsActivity extends MapActivity 
    {    
        MapView mapView; 
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
     
            mapView = (MapView) findViewById(R.id.mapView);
            LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
            View zoomView = mapView.getZoomControls(); 
     
            zoomLayout.addView(zoomView, 
                new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT)); 
            mapView.displayZoomControls(true);
     
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
    }

    Basically, you obtain the MapView instance on the activity, obtain its zoom controls and then add it to the LinearLayout element you added to the activity earlier on. In the above case, the zoom control will be displayed at the bottom of the screen. When you now press F11 in Eclipse, you will see the zoom controls when you touch the map (see Figure 4).


    Figure 4 Using the zoom controls in Google Maps

    Using the zoom control, you can zoom in or out of a location by simply touching the "+ or "-" buttons on the screen.

    Alternatively, you can also programmatically zoom in or out of the map using the zoomIn() and zoomOut() methods from the MapController class:

    package net.learn2develop.GoogleMaps;
     
    //...
    import android.os.Bundle;
    import android.view.KeyEvent;
     
    public class MapsActivity extends MapActivity 
    {    
        MapView mapView; 
     
        public boolean onKeyDown(int keyCode, KeyEvent event) 
        {
            MapController mc = mapView.getController(); 
            switch (keyCode) 
            {
                case KeyEvent.KEYCODE_3:
                    mc.zoomIn();
                    break;
                case KeyEvent.KEYCODE_1:
                    mc.zoomOut();
                    break;
            }
            return super.onKeyDown(keyCode, event);
        }    
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            //...
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
    }

    In the above code, when the user presses the number 3 on the keyboard the map will zoom in into the next level. Pressing number 1 will zoom out one level.

    Changing Views of the Map

    By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:

            mapView.setSatellite(true);

    You can also display the map in street view, using the setStreetView() method:

            mapView.setStreetView(true);

    Figure 5 shows the Google Maps displayed in satellite and street views, respectively.


    Figure 5 Displaying Google Maps in satellite and street views

    Displaying a Particular Location

    Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.

    The following code shows how this is done:

    package net.learn2develop.GoogleMaps;
     
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    import com.google.android.maps.MapView.LayoutParams;
     
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
     
    public class MapsActivity extends MapActivity 
    {    
        MapView mapView; 
        MapController mc;
        GeoPoint p;
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            mapView = (MapView) findViewById(R.id.mapView);
            LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
            View zoomView = mapView.getZoomControls(); 
     
            zoomLayout.addView(zoomView, 
                new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT)); 
            mapView.displayZoomControls(true);
     
            mc = mapView.getController();
            String coordinates[] = {"1.352566007", "103.78921587"};
            double lat = Double.parseDouble(coordinates[0]);
            double lng = Double.parseDouble(coordinates[1]);
     
            p = new GeoPoint(
                (int) (lat * 1E6), 
                (int) (lng * 1E6));
     
            mc.animateTo(p);
            mc.setZoom(17); 
            mapView.invalidate();
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
    }

    In the above code, you first obtain a controller from the MapView instance and assign it to a MapController object (mc). You use a GeoPoint object to represent a geographical location. Note that for this class the latitude and longitude of a location are represented in micro degrees. This means that they are stored as integer values. For a latitude value of 40.747778, you need to multiply it by 1e6 to obtain 40747778.

    To navigate the map to a particular location, you can use the animateTo() method of the MapController class (an instance which is obtained from the MapView object). The setZoom() method allows you to specify the zoom level in which the map is displayed. Figure 6 shows the Google Maps displaying the map of Singapore.


    Figure 6 Navigating to a particular location on the map

    Adding Markers

    Very often, you may wish to add markers to the map to indicate places of interests. Let's see how you can do this in Android. First, create a GIF image containing a pushpin (see Figure 7) and copy it into the res/drawable folder of the project. For best effect, you should make the background of the image transparent so that it does not block off parts of the map when the image is added to the map.


    Figure 7 Adding an image to the res/drawable folder

    To add a marker to the map, you first need to define a class that extends the Overlay class:

    package net.learn2develop.GoogleMaps;
     
    import java.util.List;
     
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.MapView.LayoutParams;
     
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Point;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.LinearLayout;
     
    public class MapsActivity extends MapActivity 
    {    
        MapView mapView; 
        MapController mc;
        GeoPoint p;
     
        class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, 
            boolean shadow, long when) 
            {
                super.draw(canvas, mapView, shadow);                   
     
                //---translate the GeoPoint to screen pixels---
                Point screenPts = new Point();
                mapView.getProjection().toPixels(p, screenPts);
     
                //---add the marker---
                Bitmap bmp = BitmapFactory.decodeResource(
                    getResources(), R.drawable.pushpin);            
                canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
                return true;
            }
        } 
     
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            //...
        }
     
        @Override
        protected boolean isRouteDisplayed() {
            // TODO Auto-generated method stub
            return false;
        }
    }

    In the MapOverlay class that you have defined, override the draw() method so that you can draw the pushpin image on the map. In particular, note that you need to translate the geographical location (represented by a GeoPoint object, p) into screen coordinates.

    As you want the pointed tip of the push pin to indicate the position of the location, you would need to deduct the height of the image (which is 50 pixels) from the y-coordinate of the point (see Figure 8) and draw the image at that location.


    Figure 8 Adding an image to the map

    To add the marker, create an instance of the MapOverlap class and add it to the list of overlays available on the MapView object:

        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            //...
     
            mc.animateTo(p);
            mc.setZoom(17); 
     
            //---Add a location marker---
            MapOverlay mapOverlay = new MapOverlay();
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);        
     
            mapView.invalidate();
        }

    Figure 9 shows how the pushpin looks like when added to the map.


    Figure 9 Adding a marker to the map

    Getting the Location that was touched

    After using Google Maps for a while, you may wish to know the latitude and longitude of a location corresponding to the position on the screen that you have just touched. Knowing this information is very useful as you can find out the address of a location, a process known as Geocoding (you will see how this is done in the next section).

    If you have added an overlay to the map, you can override the onTouchEvent() method within the Overlay class. This method is fired every time the user touches the map. This method has two parameters - MotionEvent and MapView. Using the MotionEvent parameter, you can know if the user has lifted his finger from the screen using the getAction() method. In the following code, if the user has touched and then lifted his finger, you will display the latitude and longitude of the location touched:

        class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, 
            boolean shadow, long when) 
            {
               //...
            }
     
            @Override
            public boolean onTouchEvent(MotionEvent event, MapView mapView) 
            {   
                //---when user lifts his finger---
                if (event.getAction() == 1) {                
                    GeoPoint p = mapView.getProjection().fromPixels(
                        (int) event.getX(),
                        (int) event.getY());
                        Toast.makeText(getBaseContext(), 
                            p.getLatitudeE6() / 1E6 + "," + 
                            p.getLongitudeE6() /1E6 , 
                            Toast.LENGTH_SHORT).show();
                }                            
                return false;
            }        
        }

    Figure 10 shows this in action.


    Figure 10 Displaying the latitude and longitude of a point touched on the map

    Geocoding and Reverse Geocoding

    If you know the latitude and longitude of a location, you can find out its address using a process known as Geocoding. Google Maps in Android supports this via the Geocoder class. The following code shows how you can find out the address of a location you have just touched using the getFromLocation() method:

        class MapOverlay extends com.google.android.maps.Overlay
        {
            @Override
            public boolean draw(Canvas canvas, MapView mapView, 
            boolean shadow, long when) 
            {
              //...
            }
     
            @Override
            public boolean onTouchEvent(MotionEvent event, MapView mapView) 
            {   
                //---when user lifts his finger---
                if (event.getAction() == 1) {                
                    GeoPoint p = mapView.getProjection().fromPixels(
                        (int) event.getX(),
                        (int) event.getY());
     
                    Geocoder geoCoder = new Geocoder(
                        getBaseContext(), Locale.getDefault());
                    try {
                        List<Address> addresses = geoCoder.getFromLocation(
                            p.getLatitudeE6()  / 1E6, 
                            p.getLongitudeE6() / 1E6, 1);
     
                        String add = "";
                        if (addresses.size() > 0) 
                        {
                            for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                                 i++)
                               add += addresses.get(0).getAddressLine(i) + "\n";
                        }
     
                        Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
                    }
                    catch (IOException e) {                
                        e.printStackTrace();
                    }   
                    return true;
                }
                else                
                    return false;
            }        
        }

    Figure 11 shows the above code in action.


    Figure 11 Performing Geocoding in Google Maps

    If you know the address of a location but want to know its latitude and longitude, you can do so via reverse-Geocoding. Again, you can use the Geocoder class for this purpose. The following code shows how you can find the exact location of the Empire State Building by using the getFromLocationName() method:

            Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
            try {
                List<Address> addresses = geoCoder.getFromLocationName(
                    "empire state building", 5);
                String add = "";
                if (addresses.size() > 0) {
                    p = new GeoPoint(
                            (int) (addresses.get(0).getLatitude() * 1E6), 
                            (int) (addresses.get(0).getLongitude() * 1E6));
                    mc.animateTo(p);    
                    mapView.invalidate();
                }    
            } catch (IOException e) {
                e.printStackTrace();
            }

    Once the location is found, the above code navigates the map to the location. Figure 12 shows the code in action.


    Figure 12 Navigating to the Empire State Building

    Summary

    In this article, you have learnt a few tricks for the Google Maps in Android. Using Google Maps, there are many interesting projects you can work on, such as geo-tagging, geo-tracking, etc. If you have cool ideas on building cool location-based services, share with us in the comments box below. Have fun!

    2010. 1. 22. 11:06

    A Visual Guide to Android GUI Widgets





    For rapid development of your user interfaces try DroidDraw

    2010. 1. 21. 14:04

    안드로이드 에뮬레이터에 가상의 SD카드 마운트시키기





    에뮬레이터 실행 버튼 클릭
    그러면 에뷸레이터가 실행된다.(꼭 실행해야 다음이 진행된다.)


    이렇게 설정을 끝낸 후, 에뮬레이터를 실행시키면 가상 SD카드가 마운트 된 채로 에뮬레이터가 실행됩니다.
    그럼, 이 SD카드에 파일을 넣어볼까요?



    이클립스에서 DDMS를 실행시킨 후, File Explorer탭을 클릭해보면 아래와 같은 아이콘이 보이실겁니다. 에뮬레이터에 파일을 넣어야하니 Push a file onto the device를 눌러줍니다.




    등록후 화면(꼭 영어로만된 파일 등록해야함)

     

    자, 저렇게 해주면 이렇게! 뿅! 들어가있는 것을 볼 수 있습니다.
    자, 그럼 이제 이 파일을 안드로이드 에뮬레이터에서 들어볼까요?
    파일을 추가했으니, 바로 음악을 듣기 전에 Dev Tools의 Media Scanner를 실행해서 파일을 인식시켜주어야 합니다.

    Media Scanner가 새로 추가된 파일을 검색중인 화면.


    검색이 끝났다면, 음악을 들어볼까요?
    Music을 눌러보시면, 다음과 같이 음악이 추가되어있는 것을 보실 수 있을 겁니다!


    음악 파일 뿐만 아니라 다른 파일을 넣을 떄에도 지금과 동일한 과정으로 수행하시면 됩니다. :)

    p.s : 이걸 통해서 삭막한 개발환경을 조금이나마 업 시킬수 있겠네요~ :)

    2010. 1. 20. 12:45

    Web View 샘플구현





    시나리오

    아래와 같은 뷰를 작성합니다.
    초기 화면은 구글 페이지를 디스플레이합니다. 
    앞으로, 뒤로 이동할 수 있어야 합니다.

     
     


    1. 프로젝트 생성
    프로젝트, 애플리케이션: WebViewingApp
    패키지: android15.samples
    액티비티: WebViewingStoryboard

    완성된 프로젝트 파일은 아래에 첨부합니다.


    2. 메인 폼 작성

    2.1 전체에 대한 레이아웃 구상
    웹뷰가 화면 전체 영역을 차지합니다.
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <WebView
            android:id="@+id/webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />
    </LinearLayout>


    웹뷰에 대한 상세사항은 다음 링크를 참조합니다.
    http://android15.tistory.com/164


    3. 애플리케이션 초기화면
    3.1 웹뷰를 다루는 멤버를 선언합니다.

    WebView _webview;

    3.2 onCreate 재정의
    웹뷰가 자바스크립트를 사용하도록 설정하고, 구글페이지를 로드합니다. 
    onCreate에 다음을 추가합니다. 
    _webview = (WebView) findViewById(R.id.webview);
    _webview.getSettings().setJavaScriptEnabled(true);
    _webview.loadUrl("http://www.google.com");

    3.3 인터넷 접근허용
    웹뷰는 인터넷을 사용해야 합니다. 인터넷은 접근허용을 받아야 하는 것입니다. 
    매니페스트 파일(AndroidMenifest.xml)을 열고, <menifest> 요소에 다음을 포함합니다.
    <uses-permission android:name="android.permission.INTERNET" />

    3.3 애플리케이션을 수행합니다.
    다 된 것처럼 보입니다.
    그러나 웹페이지의 링크를 클릭해보세요.
    우리의 웹뷰가 링크된 페이지를 보여주는 것이 아니라, 안드로이드에 기본으로 설정된 웹 브라우저가 해당 페이지를 보여줍니다.


    4. 링크된 페이지가 우리의 웹뷰안에서 로드되게 하기
    4.1 웹뷰클라이언트 재정의(WebViewClient)

    웹뷰클라이언트 클래스를 확장하는 클래스를 작성하고, shouldOverrideUrlLoading 메소드를 재정의합니다.
    true를 리턴함으로 우리의 웹뷰에서 URL을 처리했음을 알립니다.
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    4.2 웹뷰에 웹뷰클라이언트 설정
    Url을 로드하기 앞서, 웹뷰클라이언트를 설정합니다.
    onCreate 부분을 아래와 같이 수정합니다. 
    ...
    _webview.setWebViewClient(new HelloWebViewClient());
    _webview.getSettings().setJavaScriptEnabled(true);
    _webview.loadUrl("http://www.google.com");

    4.3 애플리케이션을 수행해봅니다.
    위와 같이 했을 경우, 원하는 웹페이지를 로드한 웹뷰가 나타나는 것이 아니라 바탕화면이 검정색으로 보입니다. 바탕화면이 검정색으로 보이는 것은 검정색으로 배경이 설정된 바탕 윈도우만 보이고, 그 위에 보여야할 뷰들이 보이지 않기 때문입니다.
    웹뷰를 설정했는데, 보이지 않는다는 것은 어떤 이유인지는 모르지만 웹뷰의 크기가 0이 되었거나 웹뷰를 포함하는 부모의 크기가 0이 되었다는 것을 의미합니다.  
    헬로뷰 예에서, 웹뷰의 부모인 레이아웃의 너비와 높이가 'wrap_content'로 설정되어 있으니, 만약 레이아웃이 웹뷰의 크기를 측정할 때 웹뷰의 크기가 0으로 계산된다면 부모 레이아웃의 크기도 0이 됩니다. 

    4.3.1  이 부분이 의심스러우니 레이아웃의 너비와 높이를 'fill_parent'로 설정해 봅니다.
    제대로 나옵니다.
    정말 웹뷰클라이언트를 설정했을 때 웹뷰의 크기가 커짐에도 불구하고, 레이아웃의 크기가 0이 되는 것인지는 안드로이드 소스코드를 까봐야겠네요. 


    5. 앞으로, 뒤로 이동에 대한 시나리오 구현
    왼쪽 키를 누르면 뒤로, 오른쪽 키를 누르면 앞으로 가게 합니다.
    다음과 같이 HelloWebViewClient의 shouldOverrideKeyEvent를 재정의합니다. 
    @Override
    public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
        int keyCode = event.getKeyCode();
        if ((keyCode == KeyEvent.KEYCODE_DPAD_LEFT) && _webview.canGoBack()) {
            _webview.goBack();
            return true;
        }
        else if ((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) && _webview.canGoForward()) {
            _webview.goForward();
            return true;
        }
        return false;
    }



    2010. 1. 19. 18:04

    Using java.net.URL for input stream access





    I was talking with Andrew Wills the other day about the java.io.File class. We were debating the merits of java.io.File versus just using a String to track the filename instead. Upon further reflection, it seemed that being able to open a stream from the object that was being carried around, would be useful, and this was something neither java.io.File nor String could do. I suggested possibly looking at java.net.URL.

    After we talked a little more about how java.net.URL captures both the identity and ability to open a stream needs he had, we thought about the other benefits java.net.URL might have. I suggested it could also be used for different protocols beyond just web and local files. For example FTP files might now be available for retrieval. Thinking a little more about this, I started to second guess myself. I was pretty sure FTP required more interactive work then HTTP and FILE based URLs.

    So, like any good developer I went back to my desk and began the Google search ritual. You know the drill, come up with a few keywords, and hit the search button. Then based on the results, you come up with new ways to word your search criteria, and you search again. After enough searching you sometimes come up with something useful. This was my case, I finally found a forum thread somewhere about a person having difficulty with an FTP URL. In their case, the filename had spaces in it, and it was a problem of escaping the spaces too many times. But out of that post I found the core code to use an FTP resource was not really much different from other java.net.URL work I've done. Matter of fact it looked pretty much the same. So, I created this program to test my theory out.

    import java.net.*;
    import java.io.*;
    
    public class URLReader {
    
    	public static void main(String[] args) throws Exception {
    		URL url = new URL(args[0]);
    		URLConnection uc = url.openConnection();
    
    		InputStreamReader input = new InputStreamReader(uc.getInputStream());
    		BufferedReader in = new BufferedReader(input);
    		String inputLine;
    
    		while ((inputLine = in.readLine()) != null) {
    			System.out.println(inputLine);
    		}
    
    		in.close();
    	}
    }
    

    You can then run the above code like this:

    As you can see, the same code will work with three different protocol based URLs. This can be useful when you're looking for code that is flexible in obtaining the data it needs.

    ---- Cris J H

    2010. 1. 19. 12:58

    안드로이드 ListActivity 링크소스





    SelectCurrency.java
    AnalogClock
    <AnalogClockid="@+id/clock1"android:layout_width="wrap_content"android:layout_height="wrap_content"/>
    Button
    <Button id ="@+id/button1" android:text="Label" android:layout_width="fill_parent" android:layout_height="fill_parent"/><Button id ="@+id/button2" android:text="Label" android:layout_width="fill_parent" android:layout_height="fill_parent" android:typeface="serif"/><Button id ="@+id/button3" android:text="Label" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textStyle="bold_italic"/>
    CheckBox
    <CheckBox id="@+id/plain_cb" android:text="Plain" android:layout_width="wrap_content" android:layout_height="wrap_content"/><CheckBox id="@+id/serif_cb" android:text="Serif" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif"/><CheckBox id="@+id/bold_cb" android:text="Bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold"/><CheckBox id ="@+id/italic_cb" android:text="Italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic"/>
    DatePicker
    <DatePicker android:layout_width="wrap_content" android:layout_height="wrap_content" >...// Required Java init code:DatePicker dp =      (DatePicker)this.findViewById(R.id.widget27);// for example init to 1/27/2008, no callback dp.init(2008, 0, 27, Calendar.SUNDAY, null);  ...
    DigitalClock
    <DigitalClock id="@+id/digitalclock"  android:layout_width="wrap_content"  android:layout_height="wrap_content"/>
    EditText
    <EditText id ="@+id/edittext1" android:text="EditText 1" android:layout_width="wrap_content" android:layout_height="wrap_content"/><EditText id ="@+id/button2" android:text="(206)555-1212" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif" android:phoneNumber="true"/><EditText id ="@+id/password" android:text="SuperSecret" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold_italic" android:password="true"/>
    Gallery
    <Gallery  id="@+id/gallery"  android:layout_width="wrap_content"  android:layout_height="wrap_content"/>
    ImageButton
    <ImageButton id="@+id/imagebutton"  android:src="@drawable/brush"  android:layout_width="wrap_content"  android:layout_height="wrap_content"/>
    ImageView
    <ImageView id="@+id/imagebutton"  android:src="@drawable/brush"  android:layout_width="wrap_content"  android:layout_height="wrap_content"/>
    ProgressBar
    <ProgressBar id="@+id/progress"  android:layout_width="wrap_content"  android:layout_height="wrap_content"/>
    RadioButton
    <RadioGroupid="@+id/widget1"android:layout_width="wrap_content"android:layout_height="wrap_content"xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"><RadioButtonid="@+id/widget2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Plain"android:checked="false"android:layout_gravity="left"android:layout_weight="0"></RadioButton><RadioButtonid="@+id/widget3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Serif"android:checked="true"android:layout_gravity="left"android:layout_weight="0"android:typeface="serif"></RadioButton><RadioButtonid="@+id/widget25"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Bold"android:checked="false"android:layout_weight="0"android:layout_gravity="left"android:textStyle="bold"></RadioButton><RadioButtonid="@+id/widget24"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Bold & Italic"android:checked="false"android:layout_weight="0"android:layout_gravity="left"android:textStyle="bold_italic"></RadioButton></RadioGroup>
    Spinner
    <Spinner id="@+id/widget1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="false"/>
    TextView
    <TextView id="@+id/plain" android:text="Plain" android:layout_width="wrap_content" android:layout_height="wrap_content"/><TextView id="@+id/serif" android:text="Serif" android:layout_width="wrap_content" android:layout_height="wrap_content" android:typeface="serif"/><TextView id="@+id/bold" android:text="Bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold"/><TextView id ="@+id/italic" android:text="Italic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="italic"/>
    TimePicker
    <TimePicker id="@+id/widget3" android:layout_width="wrap_content" android:layout_height="wrap_content"/>

    package com.sh;

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

    import java.util.Currency;
    import java.util.Locale;

    import android.app.ListActivity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.Toast;

    public class SelectCurrency extends ListActivity {

     String[] countries ={"aaa","bbb","ccc","ddd","eee","fff"};
     Locale[] ll;

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

      ll = Locale.getAvailableLocales();
      //countries = new String[ll.length];
      //int i = 0;
      //for (Locale loc : ll) {
      // countries[i] = loc.getDisplayCountry();
      // i++;
      //}

      setListAdapter(new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, countries));
      getListView().setTextFilterEnabled(true);
     }

     @Override
     protected void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      Context context = getApplicationContext();
      Toast.makeText(context, "Country selected: " + countries[position] +":position="+position,
        Toast.LENGTH_LONG).show();
      Intent intent = new Intent(SelectCurrency.this, PokerWinnings.class);
      startActivity(intent);
     }

    }

     

    PokerWinnings.java

     package com.sh;

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

    public class PokerWinnings extends Activity {
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      this.setContentView(R.layout.pokerwinning);
     }
    }

    main.xml
     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    </LinearLayout>
    pokerwinning.xml
     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        />
    </LinearLayout>

    AndroidManifest.xml

     <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.sh"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".SelectCurrency"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
         <activity android:label="@string/app_name" android:name=".PokerWinnings">
          <intent-filter>
           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
      </activity>
        </application>
        <uses-sdk android:minSdkVersion="6" />

    </manifest>


    strings.xml
     <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Hello World, SelectCurrency!</string>
        <string name="app_name">리스트클릭테스트</string>
    </resources>


    화면
     
     크릭후..