'자바'에 해당되는 글 22건

  1. 2011.10.17 Android - Unzip
  2. 2011.10.17 Android - Down file using http/http방식으로 파일 다운
  3. 2011.10.17 Android - Methods GET and POST in HTML forms//http전송 get방식, post방식
  4. 2011.10.17 Android - keyboard setting for when layout is hidden by keyboard popup / EditText 클릭시 UI 같이 올라가는 문제
  5. 2011.10.05 Android - WebView Debuging /get webview error code
  6. 2011.10.05 Android - Custom Swipe-Fling Scroll View / like home screen view
  7. 2011.10.05 Android - Custom Dialog Set Root Background
  8. 2011.10.05 Android - Custom CheckBox
  9. 2011.10.05 Android - Custom RadioButton
  10. 2011.10.05 Android - Custom Dialog onClick Event
  11. 2011.10.05 Android - custom indeterminate progressbar
  12. 2011.07.28 Android - Activity for result /자신을 호출한 엑티비티에게 데이터 보내기
  13. 2011.07.20 Android - Convert Raw file to OutStream / raw파일 outputstream으로 변경
  14. 2011.06.15 Android - to use json[JSONArray,JSONObject](example) /안드로이드에서 json 사용하기
  15. 2011.06.02 Android - portrait or landscape hold /화면 고정 시키기 / 회전 잠금
  16. 2011.06.01 Android - GestureDetector, fling event in code/scroll/좌우스크롤/좌우넘기기
  17. 2011.05.27 Android - view set margin in code
  18. 2011.05.27 Android - Bitmap resize
  19. 2011.05.13 Android - Bitmap, Drawable convert
  20. 2011.04.05 Android - VideoView 실시간 동영상
  21. 2011.03.31 Android - EditText 사용 시 키보드 Show/Hide
  22. 2011.01.06 Android - 문자열 자르기 StringTokenizer
posted by Full-stack Developer 2011. 10. 17. 17:37
 package com.xxx.xxx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class CUnzip {
final static int BUFFER_SIZE = 1024 * 1000;
public boolean UnzipStart(String fname ){
File zipFile = new File("/sdcard/urdir/filename.ZIP") ;
File targetDir = new File("/sdcard/dir/");
try {
return unzip(zipFile,targetDir);
} catch (Exception e) {

return false;
}
}
private boolean unzip(File zipFile, File targetDir) {
        FileInputStream fis = null;
        ZipInputStream zis = null;
        ZipEntry zentry = null;

        try {
try {

fis = new FileInputStream(zipFile);
zis = new ZipInputStream(fis);

while ((zentry = zis.getNextEntry()) != null) {
String fileNameToUnzip = zentry.getName(); 

File targetFile = new File(targetDir, fileNameToUnzip);

if (zentry.isDirectory()) {//if is Directory
File path = new File(targetFile.getAbsolutePath());
if (!path.isDirectory()) {
path.mkdirs();
}
} else { //if is File 
File path = new File(targetFile.getParent());
if (!path.isDirectory()) {
path.mkdirs();
}
unzipEntry(zis, targetFile);
}
}
} finally {
if (zis != null) {
zis.close();
}
if (fis != null) {
fis.close();
}
}
} catch (Exception e) {
return false;
}
return true;
    }
    private static File unzipEntry(ZipInputStream zis, File targetFile) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(targetFile);

            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = zis.read(buffer)) != -1) {
            if(len == 0){
            return null;
            }
                fos.write(buffer, 0, len);
            }
        } finally {
            if (fos != null) {
                fos.close();
            }
        }
        return targetFile;
    }
}

posted by Full-stack Developer 2011. 10. 17. 16:51
void downloadData(String addr){
StringBuilder html = new StringBuilder();
try{
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if(conn != null){
conn.setConnectTimeout(10000);
conn.setUseCaches(false);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
File book=new File("/sdcard/filedir", "filename.dat");
       FileOutputStream fileOutput = new FileOutputStream(book);
       InputStream inputStream = conn.getInputStream();
       int downloadedSize = 0;
       byte[] buffer = new byte[1024];
       int bufferLength = 0; 
       while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
               fileOutput.write(buffer, 0, bufferLength);
               downloadedSize += bufferLength;
       }
       fileOutput.close();
}
}
}catch(Exception ex){;}
}

안녕하세요 ^^
잠시 설명을 해볼까 합니다ㅎ

파일다운받을때 http방식으로 다운받는 로직인데요.
addr에 파일 풀경로를 넣어주시고
노란색으로 표시된부분에 다운받을실 경로와 파일명을 기입해주시면
끗!

도움이 되셨길 빌어요 ^^
즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 17. 16:32
1.Get 방식
example)

{
...
String result = sendData("http://xxx.xxx.xxx/xxx.asp?title=leeminjung&type=article");
...
}

private static String sendData(String addr){
StringBuilder html = new StringBuilder();
try{
URL url = new URL(addr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
if(conn != null){
conn.setConnectTimeout(10000);
conn.setUseCaches(false);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
for(;;){
String line = br.readLine();
if(line == null)break;
html.append(line );
html.append('\n');
}
br.close();
}
conn.disconnect();
}
}
catch(Exception ex){;}
return html.toString();


2.Post 방식

example)

{
...
   login();
... 


public void login() {
        try {
             URL url = new URL("http://xxx.xxx.xx.xx/xxxx/xxxx/xxx");      
             HttpURLConnection http = (HttpURLConnection) url.openConnection();  

             http.setDefaultUseCaches(false);                                           
             http.setDoInput(true);
             http.setDoOutput(true);
             http.setRequestMethod("POST");
             http.setRequestProperty("content-type", "application/x-www-form-urlencoded");
             
             EditText pwet = (EditText)findViewById(R.id.login_pw_edit);
             EditText idet = (EditText)findViewById(R.id.login_id_edit);

             StringBuffer buffer = new StringBuffer();
                     
buffer.append("LOGIN__USER_ID").append("=").append(idet.getText().toString()).append("&");            
             buffer.append("LOGIN__USER_PW").append("=").append(pwet.getText().toString()); 
                       
             OutputStreamWriter outStream = new OutputStreamWriter(http.getOutputStream(), "EUC-KR");
             PrintWriter writer = new PrintWriter(outStream); 
             writer.write(buffer.toString());//send data
             writer.flush();

             InputStreamReader tmp = new InputStreamReader(http.getInputStream(), "EUC-KR"); 
             BufferedReader reader = new BufferedReader(tmp);
             StringBuilder builder = new StringBuilder();
             String str;
             while ((str = reader.readLine()) != null) {
                  builder.append(str + "\n");
             }
             String  result = builder.toString();//request result
            ...
        } catch (MalformedURLException e) {;} catch (IOException e) {;} 


안녕하세요 ^^
설명을 조금 해드리겠습니다 ㅎ
우선 get방식은 경로에 위에 예제에도 나왔듯이 url에  ?변수명=데이터식으로 이어붙이기를 계속
하시면 되겠죠? 예제보시면 딱 아~ 하실꺼에요..(제 희망사항 ㅠ_ㅠ)

그리고 post방식은  2.post방식 예제에서 노란색으로 표시된 부분을 보시면 변수명 데이터 삽입한
게 보이실 거에요 ㅎ
그럼 응용하면 되겠죠?

도움 되셧길 바래요~

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 17. 16:05
<activity android:name=".xxxx"
                  android:windowSoftInputMode="adjustPan">



안녕하세요 ^^
잠깐 설명을 해보겠습니다.

 EditText가 있다면 글을 적으려고하면 UI가 위로 같이 올라가버리는 현상이 일어나죠?
이것을 없에기 위해서 EditText를 클릭하여 키보드가 올라가도 UI는 그대로 변경되지
않게 하기위한 방법입니다.

사용방법은 AndroidManifest.xml에서 해당 Activity에 위의 예제처럼 추가해주시면 됩니다.
완전 똑같이 하실필요는 없구요 ㅎ추가만해주셔도 되요 ㅎ

도움이 되셨길 바래요ㅎ

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 5. 18:46
WebView child = new WebView(this);
... 

child.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.i("MyApplication","yoon|"+cm.message() + " -- From line " + cm.lineNumber()+" of "+cm.sourceId());
return true;
}
 
});
...

안녕하세요 ^^
설명을 해볼까해요ㅎ

하이브리드앱으로 앱구현시 자바스크립트애러를 보기위해서 사용해봤는데요.
위의 예제처럼 해당 Webview에 setWebChromeClient로 세팅해주시면된답니다.

도움되셨길 바랍니다.ㅎ

즐코딩! 낫빡칙!
 

posted by Full-stack Developer 2011. 10. 5. 17:44
Step 1.create  CustomViewer.java  and custom!

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;


public class CustomViewer extends ViewGroup {
private Scroller mScroller;
private VelocityTracker mVelocityTracker;
 private int mScrollX = 0;
private int mCurrentScreen = 0;//현제 창의 위치
 private float mLastMotionX;
 private static final String LOG_TAG = "FlingAndScrollViewer";
 private static final int SNAP_VELOCITY = 1000;//속도
 private final static int TOUCH_STATE_REST = 0;
private final static int TOUCH_STATE_SCROLLING = 1;
 private int mTouchState = TOUCH_STATE_REST;
 private int mTouchSlop = 0;
 public CustomViewer(Context context) {
    super(context);
    mScroller = new Scroller(context);
     mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
     this.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.FILL_PARENT));
}
 public CustomViewer(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = getContext().obtainStyledAttributes(attrs,
            R.styleable.FlingAndScrollViewer);
    mCurrentScreen = a.getInteger(
            R.styleable.FlingAndScrollViewer_default_screen, 0);
     mScroller = new Scroller(context);
     mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
     this.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.FILL_PARENT));
 }
 public void setInitialPosition(int initialPosition){
    mCurrentScreen = initialPosition;
}
 @Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onTouchEvent will be called and we do the actual
     * scrolling there.
     */
     /*
     * Shortcut the most recurring case: the user is in the dragging state
     * and he is moving his finger. We want to intercept this motion.
     */
    final int action = ev.getAction();
    if ((action == MotionEvent.ACTION_MOVE)
            && (mTouchState != TOUCH_STATE_REST)) {
        return true;
    }
     final float x = ev.getX();
     switch (action) {
    case MotionEvent.ACTION_MOVE:
        /*
         * mIsBeingDragged == false, otherwise the shortcut would have
         * caught it. Check whether the user has moved far enough from his
         * original down touch.
         */
         /*
         * Locally do absolute value. mLastMotionX is set to the y value of
         * the down event.
         */
        final int xDiff = (int) Math.abs(x - mLastMotionX);
         boolean xMoved = xDiff > mTouchSlop;
         if (xMoved) {
            // Scroll if the user moved far enough along the X axis
            mTouchState = TOUCH_STATE_SCROLLING;
        }
        break;
     case MotionEvent.ACTION_DOWN:
        // Remember location of down touch
        mLastMotionX = x;
         /*
         * If being flinged and user touches the screen, initiate drag;
         * otherwise don't. mScroller.isFinished should be false when being
         * flinged.
         */
        mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST
                : TOUCH_STATE_SCROLLING;
        break;
     case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        // Release the drag
        mTouchState = TOUCH_STATE_REST;
        break;
    }
     /*
     * The only time we want to intercept motion events is if we are in the
     * drag mode.
     */
    return mTouchState != TOUCH_STATE_REST;
}
 @Override
public boolean onTouchEvent(MotionEvent event) {
     if (mVelocityTracker == null) {
        mVelocityTracker = VelocityTracker.obtain();
    }
    mVelocityTracker.addMovement(event);
     final int action = event.getAction();
    final float x = event.getX();
     switch (action) {
    case MotionEvent.ACTION_DOWN:
        Log.i(LOG_TAG, "event : down");
        /*
         * If being flinged and user touches, stop the fling. isFinished
         * will be false if being flinged.
         */
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
         // Remember where the motion event started
        mLastMotionX = x;
        break;
    case MotionEvent.ACTION_MOVE:
        // Log.i(LOG_TAG,"event : move");
        // if (mTouchState == TOUCH_STATE_SCROLLING) {
        // Scroll to follow the motion event
        final int deltaX = (int) (mLastMotionX - x);
        mLastMotionX = x;
         // Log.i(LOG_TAG, "event : move, deltaX " + deltaX + ", mScrollX " +
        // mScrollX);
         if (deltaX < 0) {
            if (mScrollX > 0) {
                scrollBy(Math.max(-mScrollX, deltaX), 0);
            }
        } else if (deltaX > 0) {
            final int availableToScroll = getChildAt(getChildCount() - 1)
                    .getRight() - mScrollX - getWidth();
            if (availableToScroll > 0) {
                scrollBy(Math.min(availableToScroll, deltaX), 0);
            }
        }
        // }
        break;
    case MotionEvent.ACTION_UP:
        Log.i(LOG_TAG, "event : up");
        // if (mTouchState == TOUCH_STATE_SCROLLING) {
        final VelocityTracker velocityTracker = mVelocityTracker;
        velocityTracker.computeCurrentVelocity(1000);
        int velocityX = (int) velocityTracker.getXVelocity();
         if (velocityX > SNAP_VELOCITY && mCurrentScreen > 0) {
            // Fling hard enough to move left
            snapToScreen(mCurrentScreen - 1);
        } else if (velocityX < -SNAP_VELOCITY
                && mCurrentScreen < getChildCount() - 1) {
            // Fling hard enough to move right
            snapToScreen(mCurrentScreen + 1);
        } else {
            snapToDestination();
        }
         if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
            mVelocityTracker = null;
        }
        // }
        mTouchState = TOUCH_STATE_REST;
        break;
    case MotionEvent.ACTION_CANCEL:
        Log.i(LOG_TAG, "event : cancel");
        mTouchState = TOUCH_STATE_REST;
    }
    mScrollX = this.getScrollX();
     return true;
}
 private void snapToDestination() {
    final int screenWidth = getWidth();
    final int whichScreen = (mScrollX + (screenWidth / 2)) / screenWidth;
    Log.i(LOG_TAG, "from des");
    snapToScreen(whichScreen);
}
 public void snapToScreen(int whichScreen) {
    Log.i(LOG_TAG, "snap To Screen " + whichScreen);
    mCurrentScreen = whichScreen;
    final int newX = whichScreen * getWidth();
    final int delta = newX - mScrollX;
    mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);
    invalidate();
}
 public void setToScreen(int whichScreen) {
    Log.i(LOG_TAG, "set To Screen " + whichScreen);
    mCurrentScreen = whichScreen;
    final int newX = whichScreen * getWidth();
    mScroller.startScroll(newX, 0, 0, 0, 10);
    invalidate();
}
 @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int childLeft = 0;
     final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() != View.GONE) {
            final int childWidth = child.getMeasuredWidth();
            child.layout(childLeft, 0, childLeft + childWidth,
                    child.getMeasuredHeight());
            childLeft += childWidth;
        }
    }
 }
 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
     final int width = MeasureSpec.getSize(widthMeasureSpec);
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    if (widthMode != MeasureSpec.EXACTLY) {
        throw new IllegalStateException("error mode.");
    }
     final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    if (heightMode != MeasureSpec.EXACTLY) {
        throw new IllegalStateException("error mode.");
    }
     // The children are given the same width and height as the workspace
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
    }
    Log.i(LOG_TAG, "moving to screen " + mCurrentScreen);
    scrollTo(mCurrentScreen * width, 0);
}
 @Override
public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
        mScrollX = mScroller.getCurrX();
        scrollTo(mScrollX, 0);
        postInvalidate();
    }
}
 /**
 * Return the parceable instance to be saved
 */
@Override
protected Parcelable onSaveInstanceState() {
    final SavedState state = new SavedState(super.onSaveInstanceState());
    state.currentScreen = mCurrentScreen;
    return state;
}
 /**
 * Restore the previous saved current screen
 */
@Override
protected void onRestoreInstanceState(Parcelable state) {
    SavedState savedState = (SavedState) state;
    super.onRestoreInstanceState(savedState.getSuperState());
    if (savedState.currentScreen != -1) {
        mCurrentScreen = savedState.currentScreen;
    }
}
 // ========================= INNER CLASSES ==============================
 public interface onViewChangedEvent {
    void onViewChange(int currentViewIndex);
}
 /**
 * A SavedState which save and load the current screen
 */
public static class SavedState extends BaseSavedState {
    int currentScreen = -1;
     /**
     * Internal constructor
     *
     * @param superState
     */
    SavedState(Parcelable superState) {
        super(superState);
    }
     /**
     * Private constructor
     *
     * @param in
     */
    private SavedState(Parcel in) {
        super(in);
        currentScreen = in.readInt();
    }
     /**
     * Save the current screen
     */
    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(currentScreen);
    }
     /**
     * Return a Parcelable creator
     */
    public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
        public SavedState createFromParcel(Parcel in) {
            return new SavedState(in);
        }
         public SavedState[] newArray(int size) {
            return new SavedState[size];
        }
    };
}

--------------------------------------------------------------------------------
Step 2. Add attrs
add res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomViewer">
        <attr name="default_screen" format="integer"/>
    </declare-styleable>
</resources> 
--------------------------------------------------------------------------------
Step 3. Use u r layout!
ex)res/layout/main.xml 
<com.xxxx.xxxx.CustomViewer
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/flingScrollViewer"/> 

안녕하세요 ^^
설명을 조금 해보겠습니다.

이 커스텀 UI를 사용하면 폰에서 홈스크린처럼 다음페이지,현제페이지, 전페이지를 스크롤 이동하면 모두보이는 기능입니다. 말이좀 이상한가요?
홈스크린이나 포토 갤러리와 같은 layout이라는 것입니다.

fling할때 가속도와 horizental scroll을 적절히 사용되었습니다.

도움되셧길 바랍니다.

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 5. 17:18
public class CustomDialog extends Dialog implements android.view.View.OnClickListener{
CustomDialog dlg;
public CustomDialog(Context context) {
super(context);
getWindow().setBackgroundDrawableResource(R.drawable.img_background);
setContentView(R.layout.customdialog);
dlg=this;
Button closeBtn =(Button)findViewById(R.id.customedlg_close_btn);
closeBtn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.customedlg_close_btn:
dlg.dismiss();
break;
}
}

}

안녕하세요 ^^
설명을 해볼까해요 ㅎ
커스텀으로 Dialog를 구현했을 시
배경화면을 변경하고 싶으시겠죠?
그때 위의 노란색 부분과같이 이미지변경을 하시거나
색을 변경하시거나 혹은 투명하게(Colors.TRANSPARENT) 만드실 수 있어요!

도움되셨길 바랍니다.

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 5. 17:15
1.
<CheckBox
android:id="@+id/setting_idsave_cb"
android:button="@drawable/checkbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="아이디저장"
android:textColor="#9b9d9d"
android:textSize="16px"
android:paddingRight="35px"/>

2.
dir is.. res/drawable/checkbtn.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_checked="true"
        android:drawable="@drawable/img_checked" />
    <item
        android:drawable="@drawable/img_check" />
</selecto 
 

안녕하세요 ^^
설명을 해보겠습니다!

사용방법은 1번과같이 button을 커스텀한 checkbox로 세팅해주시면됩니다.
2과같이 체그될때 이미지, 체크안될을때 이미지를 설정해주시면 끗!

도움되셧길 바랍니다 ㅎ

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 5. 16:52
1.
<RadioButton
android:id="@+id/setting_p_rb"
android:button="@drawable/radiobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="개인회원 "
android:textColor="#9b9d9d"
android:textSize="16px"
android:layout_marginBottom="5px"
android:layout_marginTop="2px"
android:paddingRight="47px"/> 

2.
dir is .. res/drawable/radiobtn.xml

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_checked="true"
        android:drawable="@drawable/i_radio_ch" />
    <item
        android:drawable="@drawable/i_radio" />
</selector> 

ch -> checked 

안녕하세요 ^^
설명을 잠시 해보겠어요.
CheckBox와 같은 방식으로 2번처럼 커스텀한 UI 1번처럼 button에 UI를 세팅해주시면 됩니다.

도움되셧길 바랍니다 ㅎ

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 10. 5. 16:47
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;

public class CustomDialog extends Dialog implements android.view.View.OnClickListener{
CustomDialog dlg;
public CustomDialog(Context context) {
super(context);
setContentView(R.layout.customdialog);
dlg=this;
Button closeBtn =(Button)findViewById(R.id.customedlg_close_btn);
closeBtn.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.customedlg_close_btn:
dlg.dismiss();
break;
}
}

}

안녕하세요 ^^
설명을 해보겠습니다.

커스텀다이얼로그를 구현할 시 클릭이벤트 생성하기가 잘안되실텐데요.
위와같이 implements를 해주시면 onclick이벤트가 생깁니다.
예제의 노란색부분을 보시면 onclick리스너를 implements 해서
onclick이벤트를 생성하여 원하는 view에 setOnClickListener를 설정해주시면
됩니다.

도움되셨길 바랍니다.ㅎ

즐코딩! 낫빡침! 


posted by Full-stack Developer 2011. 10. 5. 16:33
1.
<ProgressBar
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:paddingTop="20px"
  android:indeterminateDrawable="@drawable/loadingspin"
  android:animationResolution="1"
  />

 2.
dir is .. res/drawable/loadingspin.xml

<?xml version="1.0" encoding="utf-8"?>
 <layer-list  xmlns:android="http://schemas.android.com/apk/res/android">
 <item>
  <rotate 
  android:drawable="@drawable/loading" ------------------------------↘


  android:pivotX="50%"
  android:pivotY="50%"
  android:fromDegrees="0"
  android:toDegrees="1080"
/>
  </item>
  </layer-list>

 

안녕하세요 ^^
잠시 설명을 해보겟습니다.

2번처럼 UI를 xml를 구현해주세요. drawable에 원하시는 png로 되있는 로딩 이미지를
세팅해주시고
1번처럼 indeterminateDrawable에 구현한 UI를 세팅해주시면 됩니다.

도움되셨으면 좋겠네요 ㅎ

즐코딩! 낫빡침! 


posted by Full-stack Developer 2011. 7. 28. 17:23


1.Parent Activity


Intent intent = new Intent(nowclassname.this, childclassname.class);
startActivityForResult(intent,1); 

....

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode== 1 || resultCode==RESULT_OK){
if(data.getStringExtra("isEnd").equals("Y")){//use data
//TODO 
}
}
}


 


2.Child Activity 

public void onBackPressed() { // if child acticity end
super.onBackPressed();
Intent _intent = getIntent();
   _intent.putExtra("isEnd", "N");
   setResult(RESULT_OK,_intent);
   finish();


안녕하세요 ^^
설명을 좀 해드릴까 합니다. ㅎ

1번은 다른 Activity를 호출할 Activity입니다.
다른 Activity를 호출할때  startActivityForResult(Intent in,int requestCode)를 이용합니다. 예제에서 보듯이 requestCode로 구분할 수가 있습니다.빨간색으로 표시 했듯이 말이죠.

2번에서 보듯이 activity가 종료되는 시점에 데이터를 넣어주면 자신을 호출한 Activity에
setResult를 이용하여 데이터를 넘겨줄 수 잇습니다.

 도움이 되셨으면 좋겠네요 ㅎ

즐코딩! 낫빡침! 

 
posted by Full-stack Developer 2011. 7. 20. 11:25


getResources().openRawResourceFd(R.raw.filename).
createOutputStream();
posted by Full-stack Developer 2011. 6. 15. 17:36
1. JSONArray

{
"number":[
    1,
    2,
    3,
    4,
    5
  ] 
}


String json4arr="{\"number\":[1,2,3,4,5]}";
        try {
        int sum=0;
        JSONObject jobj = new JSONObject(json4arr);
JSONArray jarr = jobj.getJSONArray("number");
for(int i=0;i<jarr.length();i++){
int tmp=jarr.getInt(i);
if(tmp%2==1){
sum += tmp;
}
}

} catch (JSONException e) {
e.printStackTrace();


2.JSONObject

{
    "color":{
    "top":"red",
    "bottom":"black",
    "
left":"blue",
    "right":"green"
  }
 
}

String json4obj="{\"color\":{\"top\":\"red\",\"bottom\":\"black\",\"left\":\"blue\",\"right\":\"green\"}}";
        try {
        JSONObject jobj = new JSONObject(json4obj);
        JSONObject color = jobj.getJSONObject("color");
       
       
        String top_color="";
         if(color.has("left")){
        top_color=color.getString("left");
         }
} catch (JSONException e) {
e.printStackTrace();
}

 3.aptana
 트리형식으로 json데이터를 보는데 도와준다./view JSONdata to tree type

 
http://codedb.tistory.com/entry/Android-plugging-Aptana-in-eclipe-%EC%9D%B4%ED%81%B4%EB%A6%BD%EC%8A%A4%EC%97%90%EC%84%9C-aptana-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0   <- install aptana in eclipse

안녕하세요 ^^

잠시 설명을 해볼까 해요.

1번째는 json array인데요 [] 이런형식으로 데이터가 배열(array)형식으로 되어있는 데이터를 가져옵니다. 예제 json array 샘플에서 number데이터가 그러한 예이죠.

노란색으로 표현하였듯이 getJSONArray로 number데이터를 가져와 데이터타입에 맞게 index를 넣어 get해오는데요. 예제는 숫자데이터라 getInt를 사용하였는데 그부분은 잘 구미에맞게 자유자재로 사용하실꺼라고 생각해요 ㅎ

2번째는 json object인데요. getJSONObject로 데이터를 get해오죠? 그리고 has라는 부분에 노란색으로 표시하였는데요. has는 말그대로 해당데이터가 있는지 없는지 true/false로 알아내는 함수입니다. 데이터를 가져오려하는데 없다면 곤란하겠죠? 예외처리로 혹은 다른 용도로 has로 해당데이터가 존재하는지 유무를 따질때 유명하겠네요 ㅎ 

그럼 도움되셨으면 좋겠네요 ㅎ

enjoy coding! Don't be angry! 
 

 
posted by Full-stack Developer 2011. 6. 2. 14:35
1.

u r manifest file

<activity android:name=".UICommand" android:screenOrientation="portrait"
   android:configChanges="keyboardHidden|orientation"></activity>


portrait, landscape, sensor... ect..


2.

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 




 
posted by Full-stack Developer 2011. 6. 1. 18:35

@Override
 protected void onCreate(Bundle savedInstanceState) {

  gesdet = new GestureDetector(this,
    new GestureDetector.OnGestureListener()
{

     @Override
     public boolean onSingleTapUp(MotionEvent e) {
      // TODO Auto-generated method stub
      return false;
     }

     @Override
     public void onShowPress(MotionEvent e) {
      // TODO Auto-generated method stub
     }

     @Override
     public boolean onScroll(MotionEvent e1, MotionEvent e2,
       float distanceX, float distanceY) {
      // TODO Auto-generated method stub
      return false;
     }

     @Override
     public void onLongPress(MotionEvent e) {
      // TODO Auto-generated method stub
     }

     @Override
     public boolean onFling(MotionEvent e1, MotionEvent e2,
       float velocityX, float velocityY) {

      return false;
     }

     @Override
     public boolean onDown(MotionEvent e) {
      // TODO Auto-generated method stub
      return false;
     }
    });
 }

 @Override
 public boolean onTouchEvent(MotionEvent event) {
  return gesdet.onTouchEvent(event);
 }

ps. if you want doubletab event, you use GestureDetector.

posted by Full-stack Developer 2011. 5. 27. 15:23

LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
lp.setMargins(left, top, right, bottom); 
view
.setLayoutParams(lp);
posted by Full-stack Developer 2011. 5. 27. 09:39

Bitmap src = BitmapFactory.decodeResource(getResources(), id);
src= Bitmap.createScaledBitmap(src, src_width, src_height,true);
posted by Full-stack Developer 2011. 5. 13. 13:42

Bitmap -> Drawable

Bitmap bitmap = new Bitmap (...);

Drawable drawable = new BitmapDrawable(bitmap);


Drawable -> Bitmap

Bitmap bitmap = Bitmap.createBitmap(width, height, true);
Drawable iconDrawable =
packageManager.getActivityIcon(resolveInfo.activityInfo);
Canvas canvas = new Canvas(bitmap);

drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);

posted by Full-stack Developer 2011. 4. 5. 11:13
VideoView vv = (VideoView)findViewById(R.id.videoView1);
       MediaController mc =  new MediaController(this);
       vv.setVideoURI(Uri.parse("rtsp://xxxxxxxxxx/xxxxx.mp4"));
       vv.setMediaController(mc);
       vv.start();

경로가 rtsp(Real Time Streaming Protocol)경로여야 한다.
posted by Full-stack Developer 2011. 3. 31. 10:47
 
보이기
EditText editText = (EditText) findViewById(R.id.myEdit);
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// only will trigger it if no physical keyboard is open
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

숨기기
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0);

출처 http://eddykudo.com/45
posted by Full-stack Developer 2011. 1. 6. 18:01



new StringTokenizer(문자열,토큰할문자열);
ex)
      문자열 : 1|12|123|      
      토큰할문자열: |
      결과: 1
              12
              123