2011. 6. 24. 08:50 안드로이드


LayoutInflater mInflater1 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
   View mDialogLayout1 = mInflater1.inflate(
     R.layout.alert_dialog_title, null);

   LayoutInflater mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
   View mDialogLayout = mInflater.inflate(R.layout.alert_dialog, null);
   
   
   builder.setPositiveButton("다시하기",
     new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog,
        int whichButton) {

      }
     });
   builder.setNegativeButton("다시하기",
     new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog,
        int whichButton) {

      }
     });
   
   builder.setCustomTitle(mDialogLayout1);

   builder.setView(mDialogLayout);

 builder.create();




<?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="fill_parent"
 android:background="@drawable/melon_list_select_bar_longtap"
 >
 <TextView
  android:text="title"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:gravity="center_horizontal|center_vertical"
  android:textSize="24px">

 </TextView>
</LinearLayout>

posted by 욱이다
2011. 6. 23. 21:39 안드로이드
출처 : http://blog.androgames.net/10/custom-android-dialog/

그냥 여기있는 소스 그대로다
리소스는 출처에도없어서 그냥 돌아다니는 아무 리소스 해서
header.png
footer.png
key.png
title.png로 이름 바꿔서 res\drawable에다가 너어뒀다

진짜 다이얼로그에서 타이틀 색깔 바꿀라고 엄청 노력했는데 이거 한방으로 끝났다 참으로 감사하다
멜론의 겨자색 다이어로그박스가 탐났었는데 드디어 원풀어다


Main.java

package np.comp.AlertDialogTest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

/**
 * Intent intent = new Intent(Index.this, AlertDialogs.class);<br>
 * intent.putExtra(AlertDialogs.setMode, AlertDialogs.PROGRESS);<br>
 * 얼랏식으로 액티비티를 띄움.<br>
 *
 */
// 버턴을 상수값으로 지정했다.
public class Main extends Activity
{
    public static final String Mode = "MODE";
    public int setMode = 0;
    public static final String mode_InputText = "1";
    public static final String mode_Login = "2";
    private EditText edit = null;
    private Button button1 = null;
    private Button button2 = null;
    final static String PIN = "0000";
    final static int CUSTOM_DIALOG = 0;
    final static int DEFAULT_DIALOG=1;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        showDialog(CUSTOM_DIALOG);   
    }
    @Override
    public Dialog onCreateDialog(int dialogId) {
        Dialog dialog = null;
        switch (dialogId) {
            case CUSTOM_DIALOG :
                CustomDialog.Builder customBuilder = new
                    CustomDialog.Builder(Main.this);
                customBuilder.setTitle("Custom title")
                    .setMessage("Custom body")
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Main.this
                            .dismissDialog(CUSTOM_DIALOG);
                        }
                    })
                    .setPositiveButton("Confirm",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                dialog = customBuilder.create();
                break;
            case DEFAULT_DIALOG :
                AlertDialog.Builder alertBuilder = new
                    AlertDialog.Builder(Main.this);
                alertBuilder.setTitle("Default title")
                    .setMessage("Default body")
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("Confirm",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Main.this
                            .dismissDialog(DEFAULT_DIALOG);
                        }
                    });
                dialog = alertBuilder.create();
                break;
        }
        return dialog;
    }
   
}

///이부분은 그냥 다이얼로그를 상속 받아서 재정의했는데 굳이 이럴 필요없이 CustomDialog create() 이부분을 적당히 긁어서 Main의 Dialog onCreateDialog부분에다가 적용시킨다면 소스 코드가 짧게 될 수있겠다
CustomDialog.java
package np.comp.AlertDialogTest;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CustomDialog extends Dialog
{
    public CustomDialog(Context context)
    {
        super(context);
        // TODO Auto-generated constructor stub
    }
    public CustomDialog(Context context,int theme)
    {
        super(context,theme);
        // TODO Auto-generated constructor stub
    }
    public static class Builder {
         
        private Context context;
        private String title;
        private String message;
        private String positiveButtonText;
        private String negativeButtonText;
        private View contentView;
 
        private DialogInterface.OnClickListener
                        positiveButtonClickListener,
                        negativeButtonClickListener;
 
        public Builder(Context context) {
            this.context = context;
        }
 
        /**
         * Set the Dialog message from String
         * @param title
         * @return
         */
        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }
 
        /**
         * Set the Dialog message from resource
         * @param title
         * @return
         */
        public Builder setMessage(int message) {
            this.message = (String) context.getText(message);
            return this;
        }
 
        /**
         * Set the Dialog title from resource
         * @param title
         * @return
         */
        public Builder setTitle(int title) {
            this.title = (String) context.getText(title);
            return this;
        }
 
        /**
         * Set the Dialog title from String
         * @param title
         * @return
         */
        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }
 
        /**
         * Set a custom content view for the Dialog.
         * If a message is set, the contentView is not
         * added to the Dialog...
         * @param v
         * @return
         */
        public Builder setContentView(View v) {
            this.contentView = v;
            return this;
        }
        /**
         * Set the positive button resource and it's listener
         * @param positiveButtonText
         * @param listener
         * @return
         */
        public Builder setPositiveButton(int positiveButtonText,
                DialogInterface.OnClickListener listener) {
            this.positiveButtonText = (String) context
                    .getText(positiveButtonText);
            this.positiveButtonClickListener = listener;
            return this;
        }
 
        /**
         * Set the positive button text and it's listener
         * @param positiveButtonText
         * @param listener
         * @return
         */
        public Builder setPositiveButton(String positiveButtonText,
                DialogInterface.OnClickListener listener) {
            this.positiveButtonText = positiveButtonText;
            this.positiveButtonClickListener = listener;
            return this;
        }
 
        /**
         * Set the negative button resource and it's listener
         * @param negativeButtonText
         * @param listener
         * @return
         */
        public Builder setNegativeButton(int negativeButtonText,
                DialogInterface.OnClickListener listener) {
            this.negativeButtonText = (String) context
                    .getText(negativeButtonText);
            this.negativeButtonClickListener = listener;
            return this;
        }
 
        /**
         * Set the negative button text and it's listener
         * @param negativeButtonText
         * @param listener
         * @return
         */
        public Builder setNegativeButton(String negativeButtonText,
                DialogInterface.OnClickListener listener) {
            this.negativeButtonText = negativeButtonText;
            this.negativeButtonClickListener = listener;
            return this;
        }
        /**
         * Create the custom dialog
         */
        public CustomDialog create() {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // instantiate the dialog with the custom Theme
            final CustomDialog dialog = new CustomDialog(context,
                  R.style.Dialog);
            View layout = inflater.inflate(R.layout.dialog, null);
            dialog.addContentView(layout, new LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
            // set the dialog title
            ((TextView) layout.findViewById(R.id.title)).setText(title);
            // set the confirm button
            if (positiveButtonText != null) {
                ((Button) layout.findViewById(R.id.positiveButton))
                        .setText(positiveButtonText);
                if (positiveButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.positiveButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    positiveButtonClickListener.onClick(
                                            dialog,
                                            DialogInterface.BUTTON_POSITIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.positiveButton).setVisibility(
                        View.GONE);
            }
            // set the cancel button
            if (negativeButtonText != null) {
                ((Button) layout.findViewById(R.id.negativeButton))
                        .setText(negativeButtonText);
                if (negativeButtonClickListener != null) {
                    ((Button) layout.findViewById(R.id.negativeButton))
                            .setOnClickListener(new View.OnClickListener() {
                                public void onClick(View v) {
                                    positiveButtonClickListener.onClick(
                                            dialog,
                                            DialogInterface.BUTTON_NEGATIVE);
                                }
                            });
                }
            } else {
                // if no confirm button just set the visibility to GONE
                layout.findViewById(R.id.negativeButton).setVisibility(
                        View.GONE);
            }
            // set the content message
            if (message != null) {
                ((TextView) layout.findViewById(
                        R.id.message)).setText(message);
            } else if (contentView != null) {
                // if no message set
                // add the contentView to the dialog body
                ((LinearLayout) layout.findViewById(R.id.content))
                        .removeAllViews();
                ((LinearLayout) layout.findViewById(R.id.content))
                        .addView(contentView,
                                new LayoutParams(
                                        LayoutParams.WRAP_CONTENT,
                                        LayoutParams.WRAP_CONTENT));
            }
            dialog.setContentView(layout);
            return dialog;
        }
 
    }
}


<?xml version="1.0" encoding="utf-8"?>
<resources>
 <!-- 여기에서 가장 핵심은 이부분이다  보통의 다이어로그를 레이아웃으로만 커스텀 형식으로 만들다보면 다이얼로그의 테두리때문에 보기 싫어서 포기 할때가있다 하지만 이부분을 추가해서 소스 코드에 적용한다면 완전 내가 원하는 이미지로 만들어진 다이얼로그 박스를 볼수있다 -->
    <style name="Dialog" parent="android:style/Theme.Dialog">
         <item name="android:windowBackground">@null</item>
        <item name="android:windowNoTitle">true</item>
          <item name="android:windowIsFloating">true</item>
    </style>
 
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <style name="DialogText">
        <item name="android:textColor">#FF000000</item>
        <item name="android:textSize">12sp</item>
    </style>
 
    <style name="DialogText.Title">
        <item name="android:textSize">16sp</item>
        <item name="android:textStyle">bold</item>
    </style>
 
</resources>


MANIFEST.xml파일
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="np.comp.AlertDialogTest"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
       
        <activity android:name=".Main" android:configChanges="orientation"
                  
                  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
posted by 욱이다
2011. 6. 22. 16:25 안드로이드

decompile.zip

출처 : http://blog.naver.com/PostView.nhn?blogId=hks9999&logNo=30103399449

고칠려고했는데 출처의 설명이 워낙 잘되있어서 긁어왔는 정도입니다.

준비사항

1. Java SDK

  - 아래의 툴들을 실행하는데 필요한 JRE 및 JDK

  - 다운로드 : http://www.oracle.com/technetwork/java/javase/downloads/index.html

 

2. Dex2Jar( Dex -> Jar)

  - 설명 : (.Dex)파일을 Class압축파일(.Jar)로 변환

  - 다운로드 : http://code.google.com/p/dex2jar/downloads/list

  - 최신버젼 : dex2jar-0.0.7.8-SNAPSHOT.zip

  - 필요환경 : JRE(Java Runtime Enviroment) 필요

 

3. Jad(Java Decompiler)

  - Class 파일 -> 자바소스로 디컴파일

  - 다운로드 : http://www.varaneckas.com/jad

  - 최신버젼 : jad158g




디컴파일 과정 설명

 

1. 먼저 풀고자 하는 .apk파일을 압축을 해제
zip파일로 변경후 압축을 풀면된다

 

2. dex2jar툴을 사용하여 classes.dex파일을 class파일로 변환한다.
커멘트창에다가 명령어 넣음>>dex2jar classes.dex

다음으로
>>jad -d source -sjava *.class 와 같이 입력을 하자.

 옵션설명

  -d 는 source 디렉토리에 생성

  -s 는 디컴파일 되는 소스의 확장자를 java

   *.class 대상으로

xml디컴파일
set WANTFILENAME=%1%
java -jar AXMLPrinter2.jar %WANTFILENAME%.xml > %WANTFILENAME%.txt



여기보면 더 잘볼 수있게 해주는 방법이있네 

http://blog.naver.com/chanwoo0117?Redirect=Log&logNo=50162248661



posted by 욱이다
2011. 6. 20. 16:40 안드로이드
android.jar source 보이는 방법

아래의 사이트에 들어가서
맞는 소스를 다운로드해서
http://en.newinstance.it/2010/05/18/androidjar-sources/

나는 android-sdk-2.1_r1-src.jar 파일을 다운했다
압축풀어서
C:\androidsdk\platforms\android-7 에 옮겨 놓고


이클립스에서
프로젝트 properties-> Java BuildPath에서

오른쪽 탭 Libraries를 선택해서 Source attachment:android_sdk를 선택해서
Add Class Folder(?잘기억이 안나지만 여튼 .. 왼쪽에 어떤 버튼) 버튼눌러서 앞축푼 해당
폴더를 지정해주면 끝난다


그럼 요렇게 보인다는 말씀!!



posted by 욱이다
2011. 5. 20. 12:19 안드로이드

프로젝트 bin폴더의 resources.ap_ 파일을 삭제하고

프로젝트 F5누르고

다시 컴파일 하면 문제없이 ASSETS파일을 읽을 수있습니다.

 

다음 예제는 ASSETS폴더에있는 PNG를 BYTE 배열로 읽어 BITMAP으로 변환해 쓰는 예제입니다.

public static Bitmap getBitmap(String filename)
 {
  byte buf[]= getdata(filename);
  Log.i("getBitmap","buf.length"+buf.length);
  return BitmapFactory.decodeByteArray(buf, 0, buf.length);
 }
  
 public static byte[] getdata( String filename) {
  int length;

  AssetManager assetManager
  = (AssetManager)Context.getAssets();

  try {
  
   InputStream is = assetManager.open(filename,
     AssetManager.ACCESS_BUFFER);
    long filesize = is.available();
   Log.i("getdata ","filesize->"+filesize);
   
   byte[] buffer = new byte[(int) filesize];
   is.read(buffer);
   is.close();

   return buffer;
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;

 }

posted by 욱이다
2011. 5. 20. 10:44 안드로이드

api demo에는 많은 내용이 있습니다.
어디에 무슨 내용이 있는지 몰라 어플을 실행해보고
예제의 내용을 적어 봤습니다.

views /seekBar    게이지 바  (이북에서 어디까지 읽었는지와 이동을 위해 쓸수있겠다)

views/tabs /.... 탭관련 모두 다있다 (인텐트 ,아이디,아이콘 입히기)

views/TextSwitcher   텍스트가 애니메이션을 통해서 변화된다 (페이드인 페이드아웃으로 다음 텍스트로 변화)

views/WebView  웹사이트를 여러게 띄워서 볼수있다

app/activity/animation  액티비티를 줌인과 패이드 인으로 다른 액티비티로 넘어갈 수있다

app/activity/custom Dialog 다이얼로그모양을 원하는대로 작성할수있다 (액티비티로)

app/activity/custom title    타이틀 바 글자를 원하는대로 설정할 수있다

app/activity/persistent state 글자를 타이핑한것을 저장 할 수있다

app/activity/Receive Result 다른액티비티의 결과를 받아 올수있다

app/activity/translucent 액티비티를 배경을 호출하기전 액티비티 배경으로 투명하게 띄운다

app/activity/translucent blur  액티비티를 배경을 호출하기전 액티비티 배경으로 블러 먹게 띄운다



posted by 욱이다
2011. 4. 21. 16:07 안드로이드

메세지 헨들러는 메세지 큐다
런에서 들어오는 값을 메세지 큐에다가 넣어둔다
그걸 가지고 메세지 헨들러에서는
자기가 속한 클레스의 값을 메세지 받은 것을 참고하여 값을 변경시켜준다


단방향 메세지 헨들러
public class MainActivity extends Activity{
.
.
.
.
Handler handler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   super.handleMessage(msg);
   switch (msg.what) {
   case 0:

    //tv2.setText(threadCnt + "");

    // Data를 Message에 실어 보내기
     tv2.setText(msg.arg1+"");
    break;

   default:
    break;
   }
  }

 };
}

 class MyRunnable implements Runnable {

  @Override
  public void run() {
   // TODO Auto-generated method stub
   while (true) {
    try {
     threadCnt++;

     //tv2.setText(threadCnt + "");
     // Handler
     //handler.sendEmptyMessage(0);

     // handler Message에 데이타 실어 보네기
      Message msg = Message.obtain();//메세지 얻어온다 메세지 풀로 부터 얻어온다 한번 쓰고 버릴려고한다
      msg.arg1 = threadCnt;
      msg.what = 0;
      handler.sendMessage(msg);

     Thread.sleep(1000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }

  }
 }

양방향 메세지 헨들러

MainActivity 에서도 핸들러 mainHandler 를 가지고있고
MyThread 에서도 핸들러 threadHandler 를 가지고있따

MyThread에서는 mainHandler를 통해 MainActivity의 값을 변경시키고
MainActivity에서는 threadHandler를 통해 MyThread의 값을 변경시킨다


public class MainActivity extends Activity {

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

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

    findViewById(R.id.btnSquare).setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Message msg = Message.obtain();
    msg.what = 0;
    msg.arg1 = Integer.parseInt(et.getText().toString());
    myTh.threadHandler.sendMessage(msg);

   }
  });

  findViewById(R.id.btnRoot).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Message msg = Message.obtain();
    msg.what = 1;
    msg.arg1 = Integer.parseInt(et.getText().toString());
    myTh.threadHandler.sendMessage(msg);
   }
  });

  myTh = new MyThread(mainHandler);
  myTh.setDaemon(true);
  myTh.start();
 }

 Handler mainHandler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   //super.handleMessage(msg);
   System.out.println(msg.what);
   switch (msg.what) {
   case 0:
    tvResult.setText(msg.arg1 + "");
    break;
   case 1:
    
    System.out.println(((Double) msg.obj).doubleValue());
    tvResult.setText( "" + ((Double) msg.obj).doubleValue());
    break;
   default:
    break;
   }
  }
 };

}

class MyThread extends Thread {
 Handler mainHandler;

 public MyThread(Handler mainHandler) {
  this.mainHandler = mainHandler;
 }

 @Override
 public void run() {
  // TODO Auto-generated method stub
  Looper.prepare();
  Looper.loop();
 }

 public Handler threadHandler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
   // TODO Auto-generated method stub
   super.handleMessage(msg);
   Message returnMsg = Message.obtain();
   switch (msg.what) {
   case 0:
    try { Thread.sleep(100); } catch (InterruptedException e) {;}
    returnMsg.what = 0;
    returnMsg.arg1 = (msg.arg1 * msg.arg1);
    break;
   case 1:
    try { Thread.sleep(100); } catch (InterruptedException e) {;}
    returnMsg.what = 1;
    returnMsg.obj = new Double(Math.sqrt((double)msg.arg1));
    break;
   default:
    break;
   }
   mainHandler.sendMessage(returnMsg);
  }
 };
}

'안드로이드' 카테고리의 다른 글

안드로이드 assets파일 읽을때 file not found 에러  (0) 2011.05.20
android api demo 내용  (0) 2011.05.20
Alert 다이얼로그  (0) 2011.04.21
Intent  (0) 2011.04.21
안드로이드 shake 입력 결과 받기 체크  (0) 2011.03.17
posted by 욱이다
2011. 4. 21. 14:33 안드로이드

//다이얼로그 호출
showDialog(basicDialog);

  //처음  다이얼로그 생성할때 만 호출된다
 @Override
 protected Dialog onCreateDialog(int id) {}

//누를때 마다 갱신되는 거다 (onCreateDialog만들어진거 갔다 값만 수정해서 뿌려지는거다)
 @Override
 protected void onPrepareDialog(int id, Dialog dialog) {}


//다이얼로그에 레이아웃 붙이기
@Override
 protected Dialog onCreateDialog(int id) {
   final LinearLayout linear = (LinearLayout) View.inflate(this, R.layout.dialoglayout, null);
   return new AlertDialog.Builder(this)
   .setTitle("CustomDialog")
   .setIcon(R.drawable.icon)
   .setView(linear)                   ///뷰의 레이아웃을 다이얼로그에 붙인다
   .setPositiveButton("확인", new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
     // TODO Auto-generated method stub
     EditText et1 = (EditText) linear.findViewById(R.id.editText1);
     EditText et2 = (EditText) linear.findViewById(R.id.editText2);
     CheckBox cb1 = (CheckBox) linear.findViewById(R.id.checkBox1);
     
     TextView tv = (TextView) findViewById(R.id.baseText);
     tv.setText(et1.getText()+ " : "+et2.getText()+" : "+(cb1.isChecked() ? "Checked" : "UnChecked"));
    }})
   .setNegativeButton("취소", new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
     // TODO Auto-generated method stub
     TextView tv = (TextView) findViewById(R.id.baseText);
     tv.setText("취소되었습니다.");
    }}) 
   .create();
}

//dialoglayout.xml 내용
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">
 <TextView
  android:text="TextView"
  android:id="@+id/textView1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"></TextView>
 <EditText
  android:text="EditText"
  android:id="@+id/editText1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"></EditText>
 <TextView
  android:text="TextView"
  android:id="@+id/textView2"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"></TextView>
 <EditText
  android:text="EditText"
  android:id="@+id/editText2"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"></EditText>
 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <CheckBox
   android:text="CheckBox"
   android:id="@+id/checkBox1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"></CheckBox>

 </LinearLayout>
</LinearLayout>

'안드로이드' 카테고리의 다른 글

android api demo 내용  (0) 2011.05.20
MessageHandler  (0) 2011.04.21
Intent  (0) 2011.04.21
안드로이드 shake 입력 결과 받기 체크  (0) 2011.03.17
이펙트 사운드 다운로드 사이트  (0) 2010.12.21
posted by 욱이다
2011. 4. 21. 12:14 안드로이드

기본적인 명시적 호출방식
     Intent i = new Intent(HelloGallery.this, SecontActivity.class);
     startActivity(i);
Component를 통한 호출
     ComponentName cn = new ComponentName("my.andr.u8",  "my.andr.u8.SecontActivity");
     Intent i2 = new Intent();
     i2.setComponent(cn);
     startActivity(i2);

외부파일을 호출한다 (이거 대박 신기함)
     Intent i3 = new Intent("com.ioedu.android");
     startActivity(i3);
     /*Manifest를 아래 처럼해놓으면 외부 파일에서도 해당 액티비티를 실행 할수있따 
       <activity android:name="SecontActivity">
        <intent-filter>
       <action android:name="com.ioedu.android">
       </action>
       <category  android:name="android.intent.category.DEFAULT">
       < /category>
       </intent-filter>
       </activity>
      */

  전화다이얼 뜨는 인텐츠다 ,카메라 도 실행 시킬 수있다
     Intent i4 = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:1234567"));
     startActivity(i4);     
/*   Manifest.xml
     <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
*/
     
   인터넷창이 뜬다 http를 "tel:123214" 하면 전화창을 띄울수있따
     Intent i5 = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com"));
     startActivity(i5);
/*   Manifest.xml
     <uses-permission android:name="android.permission.INTERNET"></uses-permission>
*/
     



액티비티끼리 데이타 주고 받기
aActivity.java

값을 보내는 부분{
        Intent i = new Intent(this, bActivity.class);
        i.putExtra("name", "홍길동");
        startActivityForResult(i, ACTIVITY_EDIT);
    }

결과값을 기대하면서 보내는 부분{
Intent i = new Intent(this, bActivity.class);
 //결과값을 기대하는 인텐트 부른다  
startActivityForResult(i, ACTIVITY_CREATE);
}

 값이 들어오는부분
 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
       if(intent == null)
        return;
        Bundle extras = intent.getExtras();
        switch(requestCode) {
        case ACTIVITY_CREATE:
            String title = extras.getString("name");
           break;
          case ACTIVITY_EDIT:
            String editTitle = extras.getString("name");
            break;

 
.
.
.
}


bActivity.java

Intent i = getIntent();
  if(i.getExtras() != null){//받아오는 값이 있나?? 잇으면 세팅
   String s = i.getStringExtra("name").toString();
   TextView tv = (TextView)findViewById(R.id.textView1);
   tv.setText(s);
  }

  findViewById(R.id.btn_result).setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    Intent i = new Intent();//인텐트에 값을 실어 결과값을 기다리는 인텐츠에게 보낸다
    i.putExtra("name", "잘했어요");
    setResult(RESULT_OK, i);
    finish();
   }});

'안드로이드' 카테고리의 다른 글

MessageHandler  (0) 2011.04.21
Alert 다이얼로그  (0) 2011.04.21
안드로이드 shake 입력 결과 받기 체크  (0) 2011.03.17
이펙트 사운드 다운로드 사이트  (0) 2010.12.21
adb failed  (0) 2010.12.20
posted by 욱이다
2011. 3. 17. 17:24 안드로이드

긁어온 데이타  http://www.clingmarks.com/?p=25

// Need to implement SensorListener
public class ShakeActivity extends Activity implements SensorListener {
    // For shake motion detection.
    private SensorManager sensorMgr;
    private long lastUpdate = -1;
    private float x, y, z;
    private float last_x, last_y, last_z;
    private static final int SHAKE_THRESHOLD = 800;
 
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
        ...... // other initializations
	// start motion detection
	sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
	boolean accelSupported = sensorMgr.registerListener(this,
		SensorManager.SENSOR_ACCELEROMETER,
		SensorManager.SENSOR_DELAY_GAME);
 
	if (!accelSupported) {
	    // on accelerometer on this device
	    sensorMgr.unregisterListener(this,
                SensorManager.SENSOR_ACCELEROMETER);
	}
    }
 
    protected void onPause() {
	if (sensorMgr != null) {
	    sensorMgr.unregisterListener(this,
                SensorManager.SENSOR_ACCELEROMETER);
	    sensorMgr = null;
        }
	super.onPause();
    }
 
    public void onAccuracyChanged(int arg0, int arg1) {
	// TODO Auto-generated method stub
    }
 
    public void onSensorChanged(int sensor, float[] values) {
	if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
	    long curTime = System.currentTimeMillis();
	    // only allow one update every 100ms.
	    if ((curTime - lastUpdate) &gt; 100) {
		long diffTime = (curTime - lastUpdate);
		lastUpdate = curTime;
 
		x = values[SensorManager.DATA_X];
		y = values[SensorManager.DATA_Y];
		z = values[SensorManager.DATA_Z];
 
		float speed = Math.abs(x+y+z - last_x - last_y - last_z)
                              / diffTime * 10000;
		if (speed &gt; SHAKE_THRESHOLD) {
		    // yes, this is a shake action! Do something about it!
		}
		last_x = x;
		last_y = y;
		last_z = z;
	    }
	}
    }
}

'안드로이드' 카테고리의 다른 글

Alert 다이얼로그  (0) 2011.04.21
Intent  (0) 2011.04.21
이펙트 사운드 다운로드 사이트  (0) 2010.12.21
adb failed  (0) 2010.12.20
안드로이드 canvas두개쓰기  (0) 2010.10.25
posted by 욱이다
prev 1 2 3 4 5 next