2010년 5월 24일 월요일

[android]Thread 예제 입니다.

이번에는 Thread 예제다..

 

#. 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"
    />
   
    <ProgressBar
     android:id = "@+id/progress"
     style="?android:attr/progressBarStyleHorizontal"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
    />
</LinearLayout>

 

 

 

#. HandlerExample.java

 

package com.android.handlerExample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;


/**
 * Message 객체 주요 메소드
 *   a. sendMessage()               : 넘겨받은 메시지를 즉시 메시지큐의 맨 뒤에 쌓는다.
 *   b. sendMessageAtFrontOfQueue() : 메시지큐의 맨 뒤가 아닌 맨앞에 쌓는다. 고로 다음 차례에

                                                         가장 먼저 처리됨.
 *   c. sendMessageAtTime()         : 특정 시간이 되면 메세지 큐에 쌓는다.
 *   d. sendMessageDelayed()        : 특정 시간이 지난 이후에 메시지큐에 쌓는다.
 */
public class HandlerExample extends Activity
{
 
 ProgressBar bar;
 Handler handler = new Handler()
 {
  public void handleMessage(android.os.Message msg)
  {
   bar.setMax(100);
   bar.incrementProgressBy(5);  // 5씩 증가하고 추가적인 작업은 하지 않는다.
  };
 };
 
 boolean isRunning = false;
 
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        bar = (ProgressBar) findViewById(R.id.progress);
       
        Thread background = new Thread(new Runnable()
        {
   public void run()
   {
    try
    {
     for ( int i = 0; i < 20 && isRunning; i++)
     {
      Thread.sleep(1000);        // 1초간 대기후
      handler.sendMessage(handler.obtainMessage()); // handler에 message 던져준다. 이작업 20번 반복!
     }
    }
    catch (Throwable t)
    {
     // 오류가 발생하면 백그라운드 스레드를 그대로 종료.
    }
   }
  });
       
        isRunning = true;
       
        background.start();
       
    }
   
   
    @Override
    protected void onStop()
    {
     super.onStop();
     isRunning = false;
    }
}

[android] Font Example

초간단 폰트 예제다...

기본적으로 3개의 폰트를 지원한다.

위 3개도 꽤 훌륭한데 사용자가 custom 해서 쓰고싶을 경우 예제임..

간혹, 트루타입 글꼴가운데 안드로이드가 읽지 못하는 글꼴이 있음.

가능하다면 글꼴 파일 이름 모두 소문자로 사용 하는 것이 좋음.

트루타입 글꼴을 사용하여 모든 글짜를 표현하면 파일 용량이 너무 커질 수도 있으므로

꼭! 필요한 글꼴만 추가하여 사용하는 것이 좋겠다..

 

#. main.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:stretchColumns="1">
 <TableRow>
  <TextView
   android:text="sans:"
   android:layout_marginRight="4px"
   android:textSize="20sp"
  />
  <TextView
   android:id="@+id/sans"
   android:text="Hello, world!"
   android:typeface="sans"
   android:textSize="20sp"
  />
 </TableRow>
 <TableRow>
  <TextView
   android:text="serif:"
   android:layout_marginRight="4px"
   android:textSize="20sp"
  />
  <TextView
   android:id="@+id/serif"
   android:text="Hello, world!"
   android:typeface="serif"
   android:textSize="20sp"
  />
 </TableRow>
 <TableRow>
  <TextView
   android:text="monospace:"
   android:layout_marginRight="4px"
   android:textSize="20sp"
  />
  <TextView
   android:id="@+id/monospace"
   android:text="Hello, world!"
   android:typeface="monospace"
   android:textSize="20sp"
  />
 </TableRow>
 <TableRow>
  <TextView
   android:text="Custom:"
   android:layout_marginRight="4px"
   android:textSize="20sp"
  />
  <TextView
   android:id="@+id/custom"
   android:text="Hello, 안녕하세요"
   android:textSize="20sp"
  />
 </TableRow>
</TableLayout>

 

 

#. FontExample

package com.android.fontExample;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class FontExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        TextView tv = (TextView) findViewById(R.id.custom);
       
        // 원하는 글꼴 assert/디렉토리 에 포함..
        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewritter.ttf");
       
        tv.setTypeface(face);
    }
}

Dialog Example

# Dialog
  1. Simple 하게 Window창 한개 Load
  2. 메세지박스(Yes Or No)
  3. Dialog Choice(여러개중 한개 선택..)
  4. ProgressBar 진행상태바


#. DialogTest

package com.android.DialogTest;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DialogTest extends Activity {
 
 protected static final int DIALOG_SIMPLE_MESAGE = 0;
 protected static final int DIALOG_YES_NO_MESAGE = 1;
 protected static final int DIALOG_CHOICE_MESAGE = 2;
 protected static final int DIALOG_PROGRESS_MESAGE = 3;
 private int mProgress;
 private Handler mProgressHandler;
 ProgressDialog mProgressDialog;
 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button simpleDlg = (Button) findViewById(R.id.simple);
        simpleDlg.setOnClickListener(new OnClickListener()
        {
   @Override
   public void onClick(View v)
   {
    Log.v("DialogTest", "onCreate()  DIALOG_SIMPLE_MESAGE!!!!!!!");
    showDialog(DIALOG_SIMPLE_MESAGE);
   }
  });
       
        Button btnYesNo = (Button) findViewById(R.id.yesNo);
        btnYesNo.setOnClickListener(new OnClickListener()
        {
   @Override
   public void onClick(View v)
   {
    Log.v("DialogTest", "onCreate() DIALOG_YES_NO_MESAGE!!!!!!!");
    showDialog(DIALOG_YES_NO_MESAGE);
   }
  });
       
        Button btnChoice = (Button) findViewById(R.id.choice);
        btnChoice.setOnClickListener(new OnClickListener()
        {
   @Override
   public void onClick(View v)
   {
    Log.v("DialogTest", "onCreate() DIALOG_CHOICE_MESAGE!!!!!!!");
    showDialog(DIALOG_CHOICE_MESAGE);
   }
  });
       
        Button btnProgressButton = (Button)findViewById(R.id.progress);
        btnProgressButton.setOnClickListener(new OnClickListener()
        {
   @Override
   public void onClick(View v)
   {
    Log.v("DialogTest", "onCreate() DIALOG_PROGRESS_MESAGE!!!!!!!");
    showDialog(DIALOG_PROGRESS_MESAGE);
    mProgress = 0;
    mProgressDialog.setProgress(0);   // progress의 초기값을 0으로
    mProgressHandler.sendEmptyMessage(0); // 0이라는 값을 메세지 핸들러로 메세지를 보낸다.
   }
  });
       
        mProgressHandler = new Handler()
        {
         public void handleMessage(android.os.Message msg)  // 핸들러에서 메세지를 받기 위해서 반드시 이 함수를 구현..
         {
          super.handleMessage(msg);
          if ( mProgress >= 100 )
          {
           mProgressDialog.dismiss();
          }
          else
          {
           mProgress++;
           mProgressDialog.incrementProgressBy(1);     // progressbar를 1씩 증가시킴
           mProgressHandler.sendEmptyMessageDelayed(0, 100);  // 100ms후에 0이라는 값을 보낸다.
          }
         }
        };
    }
   
    @Override
    protected Dialog onCreateDialog(int id)  // showDialog에서 인자로 넘긴 아이이값이랑 동일
    {
     
     switch (id)
     {
  case DIALOG_SIMPLE_MESAGE :
   Log.v("DialogTest", "onCreateDialog DIALOG_SIMPLE_MESAGE!!!!!!!");
   // 다이얼로그를 만들고 그 다이얼로그의 윈도우를 얻어와서 타이틀을 세팅하고 보여줌.
   Dialog d = new Dialog(DialogTest.this);
   Window window = d.getWindow();
   window.setFlags(WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW, WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW);
   d.setTitle("hi");
   d.show();
   return d;
 
  case DIALOG_YES_NO_MESAGE :
   Log.v("DialogTest", "onCreateDialog DIALOG_YES_NO_MESAGE!!!!!!!");
   // AlertDialog.Builder 객체를 생성
   return new AlertDialog.Builder(DialogTest.this)
   .setIcon(R.drawable.icon)
   .setTitle("Yes,No Dlg")                  // 제목
   .setMessage("do you know me?")                // 메세지
   .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {  // OK 버튼 리스너
    public void onClick(DialogInterface dialog, int whichButton)
    {
     /* User clicked OK so do some stuff */
    }
   })
   
   .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { // cancel 버튼 리스너
    public void onClick(DialogInterface dialog, int whichButton)
    {
     /* User clicked Cancel so do some stuff */
    }
   })
   
   .create();
 
  case DIALOG_CHOICE_MESAGE :
   Log.v("DialogTest", "onCreateDialog DIALOG_CHOICE_MESAGE!!!!!!!");
   // 싱글 혹은 멀티풀 선택 가능
   return new AlertDialog.Builder(DialogTest.this)
    .setIcon(R.drawable.icon)
             .setTitle(R.string.alert_dialog_single_choice)
             .setSingleChoiceItems(R.array.alert_array, 0, new DialogInterface.OnClickListener()
             {
     @Override
     public void onClick(DialogInterface dialog, int which)
     {
      /* user... */
     }
    })
    .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener()
    {
     @Override
     public void onClick(DialogInterface dialog, int which)
     {
      /* user... */
     }
    })
    .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener()
    {
     public void onClick(DialogInterface dialog, int whichButton)
     {
                      /* User clicked No so do some stuff */
     }
    })
    .create();
 
  case DIALOG_PROGRESS_MESAGE :
   Log.v("DialogTest", "onCreateDialog DIALOG_PROGRESS_MESAGE!!!!!!!");
   // Progressbar와 함께 표현한 다이얼로그
   mProgressDialog = new ProgressDialog(DialogTest.this);
   mProgressDialog.setIcon(R.drawable.icon);
   mProgressDialog.setTitle(R.string.alert_dialog_progress);
   mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
   mProgressDialog.setMax(100);
   mProgressDialog.setButton("hide", new DialogInterface.OnClickListener()
   {
    @Override
    public void onClick(DialogInterface dialog, int which)
    {
     /* user... */
    }
   });
   
   mProgressDialog.setButton2(getText(R.string.alert_dialog_cancel), new DialogInterface.OnClickListener()
   {
    @Override
    public void onClick(DialogInterface dialog, int which)
    {
     /* user... */
    }
   });
   
   return mProgressDialog;
   
  }

     return super.onCreateDialog(id);
    }
   
   
}

 

 

 

#. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <Button
  android:id="@+id/simple"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/str_simple"
 />
 <Button
  android:id="@+id/yesNo"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/str_yesNo"
 />
 <Button
  android:id="@+id/choice"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/str_choice"
 />
 <Button
  android:id="@+id/progress"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/str_progress"
 />
</LinearLayout>


#. string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, DialogTest!</string>
    <string name="str_simple">simple_alert</string>
    <string name="str_yesNo">yesNo alert</string>
    <string name="str_choice">choice alert</string>
    <string name="str_progress">progress alert</string>
    <string name="alert_dialog_cancel">cancel</string>
    <string name="alert_dialog_ok">ok</string>
    <string name="alert_dialog_single_choice">single choice</string>
    <string name="alert_dialog_progress">Progress Dialog!</string>
</resources>


#. Arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="alert_array">
 <item>1</item>
 <item>2</item>
 <item>3</item>
 <item>4</item>
</string-array>
</resources>