[Android] Fragment 생명주기

Posted by 알 수 없는 사용자
2015. 8. 10. 09:56 프로그래밍/Android

Fragment란 ? 


Activity 는 한 화면에 보이는 전부를 칭하며 Android가 스마트폰에 발전에 따른 넓은 화면과 화려한 어플리케이션 개발을 위해서 Fragment라는 개념을 사용하기 시작했습니다.

기본 Activity 한 화면에 여러 공간으로 쪼개어 사용하거나 Activity의 이동이 없이 Activity 내부에서 다른 Layout으로 바꾸는 경우에 사용되고 있습니다.Fragment는 Android 3.0(허니컴)부터 API를 지원해 왔으며 그 이하 버전은 Support.v4의 FragmentActivity를 사용한다면 동일하게 사용가능 하다.



Fragment 특징



Fragment 클래스는 인스턴스화되고 액티비티와 연결하는 과정에 있어 프래그먼트 자체 생명주기가 작동한다.


Fragment는 Activity와 마찬가지로 Back Stack을 사용 할 수 있으나, Activity처럼 다양한 Stack방식을 지원하지 않는다.


Fragment는 여러 Activity에서 사용될 수 있으므로 Activity에 독립적으로 구현되어야 한다.


Fragment는 Activity가 아니기 때문에 context를 가지지 않는다.


Fragment 종류

DialogFragment: 떠다니는 다이얼로그를 보여주는 Fragment. Fragment는 백스택에 넣어둘 수 있기 때문에 사용자가 다시 Fragment로 복귀하고자 할 때에 Activity에 기본적으로 들어있는 다이얼로그 대신에 사용할수 있는 좋은 대체제이다. 

ListFragment: Adapter를 통해서 List를 보여주는 Fragment로 ListActivity와 비슷하고, list view에서 다룰 수 있는 onListItemClick()과 같은 콜백 함수들도 제공한다.

PreferenceFragment: Preference 객체들을 목록으로 보여주는 PreferenceActivity와 비슷하며, 앱의 Settings를 만들 때에 유용하게 사용할 수 있다.

Fragment 생명주기


FragmentTransaction으로 Fragment를 add,remove, replace 한다. 이외 레이아웃에서 바로 add하는 경우도 있다.

1. onAttach()


Fragment가 Activity에 붙을때 호출 된다.


2. onCreate()


Activity의 onCreate()와 비슷하나, UI 관련 작업은 할 수 없다.


3. onCreateView()


Fragment 와 관련 되는 View 계층을 inflater을하여 View작업을 하여 리턴합니다.


4. onActivityCreated()


Activity에서 Fragment를 모두 생성하고 난다음 호출 된다. 

Activity의 onCreate()에서 setContentView()한 다음이라고 생각 하면 쉽게 이해 될것 같다. 

여기서 부터는 UI변경작업이 가능하다.


5. onStart()


Fragment가 화면에 표시될때 호출된다. 사용자의 Action과 상호 작용 할 수 없다.


6. onResume()


Fragment가 화면에 완전히 그렸으며, 사용자의 Action과 상호 작용이 가능하다.


– 다른 Fragment가 add


1. onPause()


Fragment가 사용자의 Action과 상호 작용을 중지한다.


2. onStop()


Fragment가 화면에서 더이상 보여지지 않게 되며, Fragment기능이 중지 되었을때 호출 된다.


3. onDestoryView()


View 리소스를 해제 할수 있도록 호출된다.

backstack을 사용 했다면 Fragment를 다시 돌아 갈때 onCreateView()가 호출 된다.


– replace or backward로 removed되는 경우


4. onDestory()


Fragment상태를 완전히 종료 할 수 있도록 호출 한다.


5. onDetach()


Fragment가 Activity와 연결이 완전히 끊기기 직전에 호출 된다.


'프로그래밍 > Android' 카테고리의 다른 글

[Android] Permission, 권한  (4) 2015.08.10
[Android] Activity 생명주기  (11170) 2015.08.10
[Android Facebook SDK] 1.Facebook SDK import  (4) 2015.07.28

[Android] Activity 생명주기

Posted by 알 수 없는 사용자
2015. 8. 10. 09:55 프로그래밍/Android

Activity 란

Activity 란 사용자 인터페이스(UI)를 담당하는 응용 프로그램(Application)의 구성(Component) 기본단위입니다. 화면 하나가 한개의 Activity 이며 여러개의 뷰(View)로 구성되어있습니다. Application이 살행될때 가장 먼저 실행되는 Activity를 MainActivity라고 칭합니다. 안드로이드 시스템은 Activity의 전환으로 인해 발생하는 사항을 "back stack" 이라고 불리는 스택에 보관하여 관리하고 프로그램이 상황을 인지할수 있도록 각 액티비티의 상태에 관련된 콜백 메소드를 호출하여 현재 해당 액티비티가 어떤 상태로 변화했는지 알려주게 됩니다.

Activity 생명주기


① onCreate() 

Activity가 실행되면 가장 먼저 이 메소드가 호출됩니다.


② onStart()

onCreate() 가 호출 된 후 바로 실행됩니다. onCreate()에 의해 실행되는 것이 아닙니다.


③ onResume()

Activity가 사용자와 상호작용하기 바로 전에 호출됨


④ onPause()

반투명 또는 일부영역만 차지하는 액티비티가 호출 된 상태로, 액티비티의 일부가 화면상에 노출되고있는 상태입니다.


⑤ onStop()

액티비티가 가려지거나 숨겨졌을 때 호출됩니다.  일반적으로 홈키를 눌렀을때 어플의 상태를 생각하시면 됩니다.


⑥ onRestart()

stop상태에서 다시 액티비티가 실행되면 호출됩니다.


⑦ onDestroy()

메모리상에서 액티비티의 자원이 완전 해제될 때 호출됩니다.

즉 어플을 종료할 때 사용됩니다. 어플 종료시 자원의 해제와 같은 기능을 여기에서 주로 실행하게 됩니다.

Activity 전환 

3번째 줄에서  intent를 생성한 후 4번째 줄에서 




'프로그래밍 > Android' 카테고리의 다른 글

[Android] Permission, 권한  (4) 2015.08.10
[Android] Fragment 생명주기  (621) 2015.08.10
[Android Facebook SDK] 1.Facebook SDK import  (4) 2015.07.28

[codecademy] 3.CONDITIONALS AND CONTROL FLOW

Posted by jungbbong
2015. 8. 10. 09:51 프로그래밍/Python

CONDITIONALS AND CONTROL FLOW


Conditionals & Control Flow 1/15

Go With the Flow

분기에 대해서 배울 것임

샘플코드를 실행하여 분기가 되는것을 확인해보아라


문제

Check out the code in the editor. You'll see the type of program you'll be able to write once you've mastered control flow. Click Save & Submit to see what happens!





Conditionals & Control Flow 2/15

Compare Closely!

비교연산자 6가지

같다 ==

같지않다 !=

~보다 크다 <

~와 같거나 크다<=

~보다 작다 >

~보다 작거나 같다 >=


주의. ==와 =는 다르다, =는 변수를 세팅할때 사용


문제

Set each variable to True or False depending on what you think the result will be. For example, 1 < 2 will be True, because one is less than two.


Set bool_one equal to the result of 17 < 328

Set bool_two equal to the result of 100 == (2 * 50)

Set bool_three equal to the result of 19 <= 19

Set bool_four equal to the result of -22 >= -18

Set bool_five equal to the result of 99 != (98 + 1)





Conditionals & Control Flow 3/15

Compare... Closelier!

비교연산자를 좀더 가깝게

앞장에서 해봤던것을 바탕으로 응용


문제

Let's run through the comparators again with more complex expressions. Set each variable to True or False depending on what you think the result will be.


Set bool_one to the result of (20 - 10) > 15

Set bool_two to the result of (10 + 17) == 3**16

Set bool_three to the result of 1**2 <= -1

Set bool_four to the result of 40 * 4 >= -4

Set bool_five to the result of 100 != 10**2





Conditionals & Control Flow 4/15

How the Tables Have Turned

이예제를 통하여 True와 False의 비교결과가 세팅되는것을 배운다

3 < 5라는 명제가 True이기 때문에 bool_one에는 True가 세팅된다


문제

For each boolean value in the editor, write an expression that evaluates to that value.


Remember, comparators are: ==, !=, >, >=, <, and <=.


Use at least three different ones!


Don't just use True and False! That's cheating!





Conditionals & Control Flow 5/15

To Be and/or Not to Be

Boolean 연산자 and, or, not 세개의 특징


and : 각각의 상태가 True인것을 체크

or : 어떤 하나라도 True인것을 체크

not : 현재상태의 반대로 전환 True->False, False->True


문제

Look at the truth table in the editor. Don't worry if you don't completely get it yet—you will by the end of this section!


Click Save & Submit to continue.





Conditionals & Control Flow 6/15

and

and연산자

A and b -> a,b 모두 True여야 True를 얻을 수 있다 그렇지 않을경우 False


문제

Let's practice with and. Assign each variable to the appropriate boolean value.


Set bool_one equal to the result of False and False

Set bool_two equal to the result of -(-(-(-2))) == -2 and 4 >= 16**0.5

Set bool_three equal to the result of 19 % 4 != 300 / 10 / 10 and False

Set bool_four equal to the result of -(1**2) < 2**0 and 10 % 10 <= 20 - 10 * 2

Set bool_five equal to the result of True and True





Conditionals & Control Flow 7/15

or

or연산자

A or b -> a,b 둘중하나가 True여야 True를 얻을 수 있다, 둘다 False일 경우 False


문제

Time to practice with or!


Set bool_one equal to the result of 2**3 == 108 % 100 or 'Cleese' == 'King Arthur'

Set bool_two equal to the result of True or False

Set bool_three equal to the result of 100**0.5 >= 50 or False

Set bool_four equal to the result of True or True

Set bool_five equal to the result of 1**100 == 100**1 or 3 * 2 * 1 != 3 + 2 + 1





Conditionals & Control Flow 8/15

not

not연산자

현재 boolean상태를 반대로 전환


문제

Let's get some practice with not.


Set bool_one equal to the result of not True

Set bool_two equal to the result of not 3**4 < 4**3

Set bool_three equal to the result of not 10 % 3 <= 10 % 2

Set bool_four equal to the result of not 3**2 + 4**2 != 5**2

Set bool_five equal to the result of not not False





Conditionals & Control Flow 9/15

This and That (or This, But Not That!)

이거저거 저거이거 다섞었을때


not은 첫번째에 평가된다

and는 다음번에 평가된다

or은 마지막에 평가된다


문제

Assign True or False as appropriate for bool_one through bool_five.


Set bool_one equal to the result of False or not True and True

Set bool_two equal to the result of False and not True or True

Set bool_three equal to the result of True and not (False or False)

Set bool_four equal to the result of not not True or False and not True

Set bool_five equal to the result of False or not (True and True)





Conditionals & Control Flow 10/15

Mix 'n' Match

섞어 매치-> 연산자를 섞어서 연습

one에는 True, False값이 들어간다 이유는 boolean 연산을 했기 때문에 

문제

This time we'll give the expected result, and you'll use some combination of boolean operators to achieve that result.


Remember, the boolean operators are and, or, and not. Use each one at least once!




Conditionals & Control Flow 11/15

Conditional Statement Syntax

조건문

if문으로 분기하는것을 배울 수 있다

if문 옆에 조건이 True일경우 아래 print문이 출력된다


문제

If you think the print statement will print to the console, set response equal to 'Y'; otherwise, set response equal to 'N'.




Conditionals & Control Flow 12/15

If You're Having...

조건문과 함수

if문은 함수의 return값에 따라도 분기된다

물론 함수안에서도 조건문으로 분기가능


문제

In the editor you'll see two functions. Don't worry about anything unfamiliar. We'll explain soon enough.


Replace the underline on line 2 with an expression that returns True.

Replace the underline on line 6 with an expression that returns True.

If you do it successfully, then both "Success #1" and "Success #2" are printed.




Conditionals & Control Flow 13/15

Else Problems, I Feel Bad for You, Son...

else문

else문은 if문과 짝을 이루어 사용되는 문이다, 단일로 사용불가능

if문에서 분기되지 못했을때 무조건 else문이 호출되는 분기 문법


문제

Complete the else statements to the right. Note the indentation for each line!




Conditionals & Control Flow 14/15

I Got 99 Problems, But a Switch Ain't One

elif문

각각의 조건으로 여러가지 분기구문을 만들어 낼 수 있다




문제

01. On line 2, fill in the if statement to check if answer is greater than 5.

02. On line 4, fill in the elif so that the function outputs -1 if answer is less than 5.




Conditionals & Control Flow 15/15

The Big If

마무으리 , 복습


비교연산자


boolean연산자

분기문법


문제

Write an if statement in the_flying_circus(). It must include:


01. if, elif, and else statements;

02. At least one of and, or, or not;

03. A comparator (==, !=, <, <=, >, or >=);

04. Finally, the_flying_circus() must return True when evaluated.

Don't forget to include a : after your if statements!




PygLatin 1/11

Break It Down

알파벳(String) 가지고 놀꺼임 


문제

When you're ready to get coding, click Save and Submit. Since we took the time to write out the steps for our solution, you'll know what's coming next!




PygLatin 2/11

Ahoy! (or Should I Say Ahoyay!)

기본적인 message 출력


문제

Please print the phrase "Pig Latin".




PygLatin 3/11

Input!

입력방법


실행화면
[#콘솔] What's your name? >

문제

01. On line 4, use raw_input("Enter a word:") to ask the user to enter a word. Save the results of raw_input() in a variable called original.

02. Click Save & Submit Code

03. Type a word in the console window and press Enter (or Return).



PygLatin 4/11

Check Yourself!

문자열에 대한 체크방법



문제

Write an if statement that verifies that the string has characters.


01. Add an if statement that checks that len(original) is greater than zero. Don't forget the : at the end of the if statement!

02. If the string actually has some characters in it, print the user's word.

03. Otherwise (i.e. an else: statement), please print "empty".


You'll want to run your code multiple times, testing an empty string and a string with characters. When you're confident your code works, continue to the next exercise.




PygLatin 5/11

Check Yourself... Some More

문자열체크 더더더더



isalpha()는 알파벳인지 확인하는 함수 알파벳이면 상수 그렇지 않을경우 0

문제

Use and to add a second condition to your if statement. In addition to your existing check that the string contains characters, you should also use .isalpha() to make sure that it only contains letters.


Don't forget to keep the colon at the end of the if statement!




PygLatin 6/11

Pop Quiz!

만든코드를 테스트해보시오


문제

Take some time to test your current code. Try some inputs that should pass and some that should fail. Enter some strings that contain non-alphabetical characters and an empty string.


When you're convinced your code is ready to go, click Save & Submit to move forward!




PygLatin 7/11

Ay B C

이제부터 문자열을 가지고 바꿀 장난질을 시작할꺼임


문제

Create a variable named pyg and set it equal to the suffix 'ay'.




PygLatin 8/11

Word Up

글자 끌어올리기

글자 소문자로 변환하는 함수


문자열에 대한 index 위치

주의. 항상 0부터 시작한다


문제

Inside your if statement:


01. Create a new variable called word that holds the .lower()-case conversion of original.

02. Create a new variable called first that holds word[0], the first letter of word.




PygLatin 9/11

Move it on Back

문자열 연산


문자열은 위와 같이 변수 더하듯(주의. 숫자는 문자열로 형변환하여 더해야함) 더하여 출력 및 저장이 가능하다


문제

On a new line after where you created the first variable:


Create a new variable called new_word and set it equal to the concatenation of word, first, and pyg.




PygLatin 10/11

Ending Up

엔딩끌어올리기


s[0]은 문자열중 문자하나 [0]의 위치를 사용하겠다는 의미이다.

s[1:4]는 해당 문자열의 s의 index인 1~4까지 사용하겠다는 의미이다. print를 사용하였으니 출력하겠다는의미


문제

Set new_word equal to the slice from the 1st index all the way to the end of new_word. Use [1:len(new_word)] to do this.




PygLatin 11/11

Testing, Testing, is This Thing On?

테스트하고 마무으리


문제

When you're sure your translator is working just the way you want it, click Save & Submit Code to finish this project.





참고 : codecademy