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를 만들 때에 유용하게 사용할 수 있다.
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()
메모리상에서 액티비티의 자원이 완전 해제될 때 호출됩니다.
즉 어플을 종료할 때 사용됩니다. 어플 종료시 자원의 해제와 같은 기능을 여기에서 주로 실행하게 됩니다.
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!
실행하여 left, l, right, r을 입력하고 엔터키를 누르면 된다, 오타를 내서 분기가 되는것을 확인할 수있다
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)
문제에 나와있는 변수들의 값을 그대로 세팅하여 주면된다, 해당 변수에 들어갈 값을 말해주자면
bool_two = True
bool_three = True
bool_four = False
bool_five = False
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
문제에 나와있는 변수들의 값을 그대로 세팅하여 주면된다, 해당 변수에 들어갈 값을 말해주자면
bool_two = False
bool_three = False
bool_four = True
bool_five = False
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!
# Make me false!
bool_two = 3 <= 2
# Make me true!
bool_three = 3 > 2
# Make me false!
bool_four = 3 > 5
# Make me true!
bool_five = 2 > 1
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
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
bool_one = not True
bool_two = not 3**4 < 4**3
bool_three = not 10 % 3 <= 10 % 2
bool_four = not 3**2 + 4**2 != 5**2
bool_five = 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)
bool_one = False or not True and True
bool_two = False and not True or True
bool_three = True and not (False or False)
bool_four = not not True or False and not True
bool_five = 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!
bool_two = (2 <= 2) or "Alpha" == "Bravo"
bool_three = not (2 <= 2) and "Alpha" == "Bravo"
bool_four = (2 == 2) and not ("Alpha" == "Bravo")
bool_five = (2 <= 2) and "Alpha" != "Bravo"
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'.
response = 'Y'
answer = "Left"
if answer == "Left":
print "This is the Verbal Abuse Room, you heap of parrot droppings!"
# Will the above print statement print to the console?
# Set response to 'Y' if you think so, and 'N' if you think not.
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.
def using_control_once():
if True:
return "Success #1"
def using_control_again():
if True:
return "Success #2"
print using_control_once()
print using_control_again()
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!
answer = "'Tis but a scratch!"
def black_knight():
if answer == "'Tis but a scratch!":
return True
else:
return False # Make sure this returns False
def french_soldier():
if answer == "Go away, or I shall taunt you a second time!":
return True
else:
return False # Make sure this returns False
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.
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
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!
# Make sure that the_flying_circus() returns True
def the_flying_circus():
if 3 < 5: # Start coding here!
# Don't forget to indent
# the code inside this block!
return True
elif 3 > 2:
# Keep going here.
# You'll want to add the else statement, too!
return True
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".
print "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).
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word:")
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.
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word:")
if len(original) > 0:
print original
else:
print "empty"
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!
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input("Enter a word:")
if original.isalpha()> 0:
print original
else:
print "empty"
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'.
pyg = '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.
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
else:
print 'empty'
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.
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
new_word = word+first + pyg
else:
print 'empty'
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.
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
word = original.lower()
first = word[0]
new_word = word+first + pyg
new_word = new_word[1:len(new_word)]
else:
print 'empty'
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.