달력

5

« 2024/5 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
반응형
728x90
반응형

[android] 날짜와 시간을 위젯으로 입력받기

안녕하세요?
프쟁이 입니다.

이 샘플소스는 안드로이드 설치폴더에 android-sdk-windows/samples/android-8/ApiDemos 위치에 원본소스가 있습니다.

날짜와 시간값을 입력받는 위젯을 버튼을 클릭했을때 입력창을 띄워서,

액티비티 화면에 입력받은 날짜와 시간값을 표시하고 갱신합니다.

먼저 원하시는 패키지 경로에 DateWidgets1.java 액티비티 클래스 파일을 추가합니다.

/*
* Copyright (C) 2007 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 net.korsoft.Test022;

import net.korsoft.Test022.R;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.view.View;

import java.util.Calendar;

/**
* Basic example of using date and time widgets, including
* {@link android.app.TimePickerDialog} and {@link android.widget.DatePicker}.
*
* Also provides a good example of using {@link Activity#onCreateDialog},
* {@link Activity#onPrepareDialog} and {@link Activity#showDialog} to have the
* activity automatically save and restore the state of the dialogs.
*
* 날짜와 시간값을 입력받는 위젯을 버튼을 클릭했을때 입력창을 띄워서,
* 입력받은 값으로 날짜와 시간값을 적용합니다.
*/
public class DateWidgets1 extends Activity {

// where we display the selected date and time
private TextView mDateDisplay;

// date and time
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;

static final int TIME_DIALOG_ID = 0;
static final int DATE_DIALOG_ID = 1;

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

setContentView(R.layout.date_widgets_example_1);

mDateDisplay = (TextView) findViewById(R.id.dateDisplay);

Button pickDate = (Button) findViewById(R.id.pickDate);
pickDate.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
//밑에 다이얼로그를 띄우는 메소드에서, DATE_DIALOG_ID
//상수값에 해당되는 다이얼로그를 띄우게 됩니다.
//날짜를 입력받는 위젯을 띄우게 됩니다.
showDialog(DATE_DIALOG_ID);
}
});

Button pickTime = (Button) findViewById(R.id.pickTime);
pickTime.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
//밑에 다이얼로그를 띄우는 메소드에서, TIME_DIALOG_ID
//상수값에 해당되는 다이얼로그를 띄우게 됩니다.
//시간을 입력받는 위젯을 띄우게 됩니다.
showDialog(TIME_DIALOG_ID);
}
});

//초기 날짜값 설정
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

//변수에 수정된 날짜값을 화면에 갱시표시..
updateDisplay();
}

/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
* 다이얼로그를 생성할때, 두 상수값에 따라서 시간과 날짜 다이얼로그를 생성
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
mTimeSetListener, mHour, mMinute, false);
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}

/*
* (non-Javadoc)
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
* 다이얼로그를 띄우기 전에, 다이얼로그에 표시될 값을 설정합니다.
* 현재 변수값에 있는 날짜와 시간값을 가져와서 위젯 다이얼로그에 설정합니다.
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case TIME_DIALOG_ID:
((TimePickerDialog) dialog).updateTime(mHour, mMinute);
break;
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
break;
}
}

// 위젯 입력다이얼로그에서 입력받은 날짜와 시간값이 변수에 저장이 되엇고,
// 변수에 저장된 날짜와 시간값을 이 메소드에서 텍스트뷰에 갱신하여 표시합니다.
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" ")
.append(pad(mHour)).append(":")
.append(pad(mMinute)));
}

/*
* 날짜입력 위젯에서 설정버튼을 눌렀을때 이벤트 처리를 하고 있습니다.
* 입력받은 값을 파라미터로 가져와서, 변수에 저장하고, 텍스트뷰에 시간값을 갱신합니다.
*/
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener()
{

public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};

/*
* 시간입력 위젯을 띄우고, 값을 입력하고서 설정버튼을 눌렀을때, 이벤트 처리를 합니다.
* 입력받은 시간값을 파라미터로 받아와서, 변수에 저장하고 화면에 시간값을 갱신합니다.
*/
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
updateDisplay();
}
};

/*
* 월/일/분/초를 표시할때 00 두자리 숫자로 표시할때 사용하는 메소드입니다.
*/
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}

레이아웃 xml 파일을, /res/layout/date_widgets_example_1.xml 파일을 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 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.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="@+id/dateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_dateDisplay_text"/>
</LinearLayout>

<Button android:id="@+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_pickDate_text"/>

<Button android:id="@+id/pickTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date_widgets_example_pickTime_text"/>

</LinearLayout>


문자열 리소스 파일인, /res/values/strings.xml 파일을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Test022Activity!</string>
<string name="app_name">Test022</string>
<string name="date_widgets_example_dateDisplay_text"></string>
<string name="date_widgets_example_pickTime_text">change the time</string>
<string name="date_widgets_example_pickDate_text">change the date</string>
</resources>


AndroidManifest.xml 파일을 설정합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.korsoft.Test022"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />

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

<activity android:name=".DateWidgets1" android:label="Views/Date Widgets/1. Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

728x90
반응형
:
Posted by mapagilove
728x90
반응형

안드로이드 개발을 하다보면 XML은 거의 필수적(?)으로 건드리는 경우가 많습니다.
물론 XML을 사용하지 않고 그냥 java 코드만으로 이루어진 프로젝트들도 많이 있지만,
XML을 사용할 경우 좀 더 간편하고 쉽게 어플리케이션의 레이아웃을 만들 수 있습니다.

개인적으로 가장 좋은 방법은 가중치(weight)를 줘서 화면 크기에 관계없는 레이아웃을 작성하는 것이
가장 좋다고 생각하지만...

[안드로이드] 화면 해상도에 관계없는 레이아웃(Layout) 만들기 - http://snowbora.com/422


가중치를 이용할 경우 XML 코드가 복잡해지고 가독성이 떨어지는 단점이 있습니다.
사실 dp(dip) 단위를 사용해도 다양한 디바이스들의 화면 해상도에 큰 영향을 안 받아야 하지만,
삼성의 갤럭시탭7인치를 비롯해서, 너무 괴상한 해상도의 디바이스들이 많아져서 dp(dip) 단위의
효용성이 많이 줄어들었습니다. 하지만, 그래도 알아두면 나쁠 건 없으니....;;;
한 번 나열해보도록 하겠습니다.


1.px
픽셀 단위. 화면의 1픽셀을 나타냅니다. 간단한 프로젝트에서는 오히려 사용하기 편할 수도 있습니다.

2. pt
포인트. 일반적으로 폰트 크기에서 사용합니다. 밀리미터나 인치처럼 모바일내가 아닌 바깥에서의 크기 단위입니다.
인치로 환산하면 1/72 인치입니다.

3. dp (dip)
dp라고 하든 dip라고 하든 상관없습니다. 화면의 dpi 크기가 160dpi 일 때, 1 dp는 1 픽셀입니다.
조금 추상적인 의미라서 사용하기 어렵기도 하고, 정확하지도 않습니다. -_-;;
하지만, 그나마 다양한 해상도를 지원하기 유용한 단위라고 볼 수도 있습니다.

px 단위와의 환산은 dip = px * (160 / density) 입니다.
만약, 480x800 단말기라고 하면, 480x800 단말의 dpi(density)는 240이기 때문에
환산 공식은 dip = px * (160/240) = px * (2/3) 가 됩니다.

4. sp
스케일과 독립적인 픽셀 크기입니다. dp 처럼 유동적인 크기이며, 주로 폰트 크기 단위로 많이 사용됩니다.

5. in
1 인치를 뜻합니다. 모바일 상에서의 크기가 아닌, 실제 1 인치 크기를 나타냅니다.
좀 애매한 단위겠죠? ^^; 1 인치는 2.54 cm입니다.

6. mm
1 밀리미터를 의미합니다.



정답은 없지만, 아무래도 그나마 추천드리는 단위는
크기로는 dp, 폰트에는 sp 단위를 쓰는 것이 가장 좋다고 생각합니다.
경우에 따라서는 px 단위까지는 쓸만한 것 같습니다.

728x90
반응형
:
Posted by mapagilove
728x90
반응형

SD Card 폴더 생성하기

Android/File

 

먼저 SD Card에 사용을 위해 퍼미션을 줘야한다.

 

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

 

 

import java.io.*;
import android.app.*;
import android.os.*;
import android.widget.*;

public class SDTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

String str = Environment.getExternalStorageState();
if ( str.equals(Environment.MEDIA_MOUNTED)) {

String dirPath = "/sdcard/android/data/pe.berabue.sdtest/temp";
File file = new File(dirPath);
if( !file.exists() ) // 원하는 경로에 폴더가 있는지 확인
file.mkdirs();
}
else
Toast.makeText(SDTest.this, "SD Card 인식 실패", Toast.LENGTH_SHORT).show();
}
}

 

 

 

file.mkdirs() file.mkdir()의 차이점

 

mkdirs()는 원하는 경로의 상위 폴더가 없으면 상위 폴더까지 생성.

ex ) sdcard/android/data/aaa/bbb

bbb 폴더를 만드려는데 aaa폴더가 없다면 aaa 폴더까지 생성 한다.

 

mkdir()은 지정 폴더만 생성.

 

 

 

구글에서 권장하는 폴더명은

 

android/data/패키지명/폴더명

 

 

728x90
반응형
:
Posted by mapagilove
728x90
반응형

안드로이드 - [Android] 전체화면 투명 Activity  안드로이드 / 개발  2011/07/30 11:07

 http://blog.naver.com/gh2501/133922225


 
출처 : http://eddykudo.com/105

 


AndroidManifest.xml 파일에서

 

  <activity android:name=".SampleTransActivity" android:screenOrientation="landscape"
   android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
   android:label="@string/app_name"
   android:configChanges="orientation|keyboardHidden">
  </activity>
[출처] 안드로이드 - [Android] 전체화면 투명 Activity|작성자 실바

728x90
반응형
:
Posted by mapagilove
728x90
반응형

Java에서, 숫자 제곱 함수 사용 방법


소스 파일명: Example.java
public class Example {
public static void main(String[] args) {


////////////////////////////////////////////////
// 3의 제곱 (3의 2승) 구하기
System.out.println( Math.pow(3, 2) );
// 출력 결과: 9.0



////////////////////////////////////////////////
// 5의 세제곱 (5의 3승) 구하기
double result;
double i = 5;
double j = 3;

result = Math.pow(i, j);
System.out.println(result);
// 출력 결과: 125.0



////////////////////////////////////////////////
// 3의 네제곱 (3의 4승) 구하기
// 출력을 정수형으로 변환하기
int result2;
int i2 = 3;
int j2 = 4;

result2 = (int) Math.pow(i2, j2);
System.out.println(result2);
// 출력 결과: 81



}
}

 

728x90
반응형
:
Posted by mapagilove
728x90
반응형

SD Card 폴더 생성하기

Android/File

 

먼저 SD Card에 사용을 위해 퍼미션을 줘야한다.

 

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

 

 

import java.io.*;
import android.app.*;
import android.os.*;
import android.widget.*;

public class SDTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

String str = Environment.getExternalStorageState();
if ( str.equals(Environment.MEDIA_MOUNTED)) {

String dirPath = "/sdcard/android/data/pe.berabue.sdtest/temp";
File file = new File(dirPath);
if( !file.exists() ) // 원하는 경로에 폴더가 있는지 확인
file.mkdirs();
}
else
Toast.makeText(SDTest.this, "SD Card 인식 실패", Toast.LENGTH_SHORT).show();
}
}

 

 

 

file.mkdirs() file.mkdir()의 차이점

 

mkdirs()는 원하는 경로의 상위 폴더가 없으면 상위 폴더까지 생성.

ex ) sdcard/android/data/aaa/bbb

bbb 폴더를 만드려는데 aaa폴더가 없다면 aaa 폴더까지 생성 한다.

 

mkdir()은 지정 폴더만 생성.

 

 

 

구글에서 권장하는 폴더명은

 

android/data/패키지명/폴더명

 

 

 

 

728x90
반응형
:
Posted by mapagilove
반응형