첫번째로 Create Project하고 화면 껍데기는 만들었음

이번에는 메뉴를 추가하고 Click 됐는지 확인만 한다.


총 15개의 TODO


<!--TODO (1) Add a string resource called search with the title "Search"-->

app > res > values > strings.xml에 search 라는 단어 추가

<resources>
    <string name="app_name">GithubSearch</string>

    <!--TODO (1) Add a string resource called search with the title "Search"-->
    <string name="search">Search</string>
</resources>
 


// Do 2 - 7 in menu.xml

// TODO (2) Create a menu xml called 'main.xml' in the res->menu folder
// TODO (3) Add one menu item to your menu

메뉴는 기본 프로젝트 생성에서 만들어지지 않기 때문에 직접 만들어야 한다.


왼쪽 프로젝트의 app 에서 오른쪽 버튼 클릭 Android Resource File 클릭

팝업으로 나타난 New Resource File 에
file name은 main으로 하고

Resouce type 은 Menu로 선택한다.(다른것을 선택하면 다른 폴더에 생성 됨)

생성이 끝나면 res > menu > main.xml 파일이 생성되어 있다.

여기에 사용할 menu를 정의한다.




// TODO (4) Give the menu item an id of @+id/action_search
// TODO (5) Set the orderInCategory to 1
// TODO (6) Show this item if there is room (use app:showAsAction, not android:showAsAction)
// TODO (7) Set the title to the search string ("Search") from strings.xml

main.xml 에서 item을 추가

menu item에 id 설정

정렬 순서(order in category) 설정

show as action 설정

버튼 text=search 설정 : string.xml에 있는 값을 사용

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:orderInCategory="1"
        app:showAsAction="ifRoom"
        android:title="@string/search"/>

</menu> 


다음부터는 MainActivity.java에서


// TODO (8) Override onCreateOptionsMenu
   

onCreateOptionsMenu method를 추가(Override)

import android.view.Menu;

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;


// TODO (9) Within onCreateOptionsMenu, use getMenuInflater().inflate to inflate the menu
// TODO (10) Return true to display your menu

그 안에서 추가한 item 설정

전체소스: TODO 8,9,10

onCreateOptionsMenu 가 return type이 boolean이기 때문에

return true 또는 false로 지정해야함.

TODO 10에서 return true;로 하면서 화면에 보이도록 한다고 설정한 것임.

// TODO (8) Override onCreateOptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO (9) Within onCreateOptionsMenu, use getMenuInflater().inflate to inflate the menu
    getMenuInflater().inflate(R.menu.main, menu);
    // TODO (10) Return true to display your menu
    return true;


메뉴를 추가했으면 해당 메뉴를 선택했을 때 어떻게 동작하는지 정의가 필요

// TODO (11) Override onOptionsItemSelected

onOptionsItemSelected method를 추가(Override)

import android.view.MenuItem;

...

@Override
public boolean onOptionsItemSelected(MenuItem item){
    return false;
}


onOptionsItemSelected 안에서 선택된 item의 id를 확인하고
search 면 임시로 toast message 표시.

toast message 표시할 때에는 반드시   .show() 를 사용해야 함.

// TODO (12) Within onOptionsItemSelected, get the ID of the item that was selected
// TODO (13) If the item's ID is R.id.action_search, show a Toast and return true to tell Android that you've handled this menu click
// TODO (14) Don't forgot to call .show() on your Toast
// TODO (15) If you do NOT handle the menu click, return super.onOptionsItemSelected to let Android handle the menu click

import android.content.Context;
import android.widget.Toast;

...

// TODO (11) Override onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item){
    // TODO (12) Within onOptionsItemSelected, get the ID of the item that was selected
    int itemThatWasClickedId = item.getItemId();

    // TODO (13) If the item's ID is R.id.action_search, show a Toast and return true to tell Android that you've handled this menu click
    if (itemThatWasClickedId == R.id.action_search) {
        Context context = MainActivity.this;
        String textToShow = "Search clicked";
        // TODO (14) Don't forgot to call .show() on your Toast
        Toast.makeText(context, textToShow, Toast.LENGTH_SHORT).show();
        return true;
    }

    // TODO (15) If you do NOT handle the menu click, return super.onOptionsItemSelected to let Android handle the menu click
    return super.onOptionsItemSelected(item);
}



실행시켜보면

상단에 menu로 SEARCH 가 있고 그것을 클릭했을 때

toast message로 'Search clicked' 가 나타남.



728x90

첫번째 App은 장난감 목록을 보여주는 것인데

ToyBox라는 class에 있는 것들을 보여주는 것이었다.


두번째 App : Github-Repo-Search

Github에 있는 project를 검색하여 해당 목록을 보여주는 것이다.

network통신 및 parsing 작업


Ex1에서는 프로젝트 생성이다.

T01 프로젝트와 같이 프로젝트 생성

예제 프로젝트의 TODO 를 Complete 하면 된다.

- activity_main.xml 에서 25개

- MainActivity.java 에서 6개

- build.gradle에서 1개

총 3개의 파일에 32개의 TODO가 있다.

먼저 activity_main.xml

<!--TODO (1) Change the ConstraintLayout to a LinearLayout-->
<!--TODO (2) Make the orientation vertical-->
<!--TODO (3) Give left, right, and top padding of 16dp-->
<!--TODO (4) Remove the line that declares the id, we don't need it-->
<!--TODO (5) Remove the xmlns:app declaration, we don't need that anymore-->

ConstraintLayout -> LinearLayout 로 바꾼다.

이때 LinearLayout은 한줄로 세우는 것이므로 가로로 세울지 세로로 세울지 지정해야한다

orientation=vertical 은 세로, horizontal은 가로

왼쪽,오른쪽,위,아래 여백 설정(16dp)

android:id=activity_main은 필요없으므로 제거

xmlns:app 도 필요없으므로

 <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

...

</android.support.constraint.ConstraintLayout>

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"

    tools:context=".MainActivity">
</LinearLayout>

...

</LinearLayout>


<!--TODO (6) Delete this TextView-->

기본으로 정의 된 Hello World TextView를 제거한다.

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 


<!--TODO (7) Add an EditText-->
<!--TODO (8) Give the EditText an id of @+id/et_search_box-->
<!--TODO (9) Set the text size to 22sp-->
<!--TODO (10) Set the width to match_parent and the height to wrap_content-->
<!--TODO (11) Provide a hint telling the user to enter a query and then click search-->

EditText를 추가하고

id 설정하고

text size=22sp

width, height 설정

hint 넣기 : edit text에 아무것도 입력이 안되었을 때 가이드하는 문장

<EditText
    android:id="@+id/et_search_box"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter a query, then click Search"
    android:textSize="22sp" /> 


<!--TODO (12) Add a TextView-->
<!--TODO (13) Give the TextView an id of @+id/tv_url_display-->
<!--TODO (14) Set the text size to 22sp-->
<!--TODO (15) Set the width to wrap_content and the height to wrap_content-->
<!--TODO (16) Give the TextView a top margin of 8dp-->
<!--TODO (17) Set the text to tell the user their search URL will show up here when they click search-->

TextView 추가

id 설정

text size=22sp

width, height

margin 설정

textview에 표시할 글자 'Click search and your URL will show up here!' 설정

<TextView
    android:id="@+id/tv_url_display"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="Click search and your URL will show up here!"
    android:textSize="22sp" /> 


<!--TODO (18) Add a ScrollView-->
<!--TODO (19) Set the width to match_parent and the height to wrap_content-->
<!--TODO (20) Set the top margin to 16dp-->

Scrollview 추가

width, height, margin 설정

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp">
   
</ScrollView> 


<!--TODO (21) Within the ScrollView, add a TextView-->
<!--TODO (22) Give the TextView an id of @+id/tv_github_search_results_json-->
<!--TODO (23) Set the text size to 18sp-->
<!--TODO (24) Set the height and width to wrap_content-->
<!--TODO (25) Set the text to something that tells the user to make a search-->

ScrollView 안에 TextView 추가

id 설정

textsize=18

width, height 설정

textview에 표시할 글씨 'Make a Search!' 설정

(scrollView는 이미 추가했으므로 TextView만 ScrollView아래에 추가한다)

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp">
    <TextView
        android:id="@+id/tv_github_search_results_json"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Make a search!"
        android:textSize="18sp" />

</ScrollView> 


여기까지 main_activity.xml


MainActivity.java에서 나머지 TODO

// TODO (26) Create an EditText variable called mSearchBoxEditText
// TODO (27) Create a TextView variable called mUrlDisplayTextView
// TODO (28) Create a TextView variable called mSearchResultsTextView

사용자 입력 EditText 변수 정의

조회된 내용 중 url 표시 TextView 변수 정의

조회결과 TextView 변수 정의

import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    // TODO (26) Create an EditText variable called mSearchBoxEditText
    private EditText mSearchBoxEditText;
    // TODO (27) Create a TextView variable called mUrlDisplayTextView
    private TextView mUrlDisplayTextView;
    // TODO (28) Create a TextView variable called mSearchResultsTextView
    private TextView mSearchResultsTextView;

...   
}


// TODO (29) Use findViewById to get a reference to mSearchBoxEditText
// TODO (30) Use findViewById to get a reference to mUrlDisplayTextView
// TODO (31) Use findViewById to get a reference to mSearchResultsTextView

onCreate Method 안에서

editText 변수에 xml에 정의 된 EditText 연결

TextView 변수에 xml에 정의 된 TextView 연결


 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // TODO (29) Use findViewById to get a reference to mSearchBoxEditText
    mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);

    // TODO (30) Use findViewById to get a reference to mUrlDisplayTextView
    mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);

    // TODO (31) Use findViewById to get a reference to mSearchResultsTextView
    mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);
}


마지막으로

settings.gradle 파일 수정

// TODO (32) Remove the ConstraintLayout dependency as we aren't using it for these simple projects


맨 처음에 ConstraintLayout 을 LinearLayout으로 바꿨음.

없애지 않아도 무관하나 깔끔하게 제거.

ConstraintLayout은 기본Layout이 아니라 android.support를 통해 제공되므로 불필요함.

자동으로 수정되어 include:app 만 있는 경우는 그냥 진행하면 됨.

원래는 setting.gradle에 아래와 같이 정의되어 있음.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.1.0'

    // TODO (32) Remove the ConstraintLayout dependency as we aren't using it for these simple projects
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'



모든 수정이 끝났으면 실행

필요한 항목만 만들어놓은 껍데기 이므로 실제 동작하지 않음.

조회버튼과 입력된 내용으로 검색하는 로직은 다음 프로젝트에서 계속...

728x90

EX1 : 프로젝트 생성, Textview 추가

EX2 : TextView에 내용 넣기


ToyList를 보면 수 많은 장난감이 있으나 실제 보이는 장남감 갯수는 처음 몇 개 뿐이다.


화면길이를 넘어가기 때문인데

이 경우 ScrollView로 감싸주면 해결된다.


TODO 확인


<!--TODO (1) Add a ScrollView around the TextView so you can scroll through the list of toys-->

ScrollView로 TextView를 감싼다.

<ScrollView
        android:layout_width=""
        android:layout_height="">
        <TextView...>
</ScrollView>


<!--TODO (2) Make the width of the ScrollView match_parent and the height wrap_content-->

ScrollView내 속성을 width=match_parent, height=wrap_content 로 한다.


<ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


전체 소스

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_toy_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:padding="16dp"
android:textSize="20sp" />
</ScrollView>
</FrameLayout>


실행해보면 Scroll이되어 모든 장난감 목록을 볼 수 있다.


728x90

첫번째 프로젝트에서는 프로젝트 생성하고 layout을 변경했으니

두번째 프로젝트에서는 Toylist를 보여주는 것을 한다.


Excercise 에서 Todo 를 확인한다.

만들던 프로젝트에서 쭉 해도 되고

Excercise를 수정해도 된다.

만들던 프로젝트에는 Todo가 표시되지 않으니 알아서 선택.


MainActivity 에 ToDo1

    // TODO (1) Declare a TextView variable called mToysListTextView
    private TextView mToysListTextView;


activity_main.xml 에 ToDo2 tv_toy_names 추가

before

 after

 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:padding="16dp"
    android:textSize="20sp" />

 <TextView
    android:id="@+id/tv_toy_names"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="20sp" />


MainActivity 에 ToDo3

onCreate method 에서 Textview와 mToysListTextView 연결


// TODO (3) Use findViewById to get a reference to the TextView from the layout

mToysListTextView = (TextView) findViewById(R.id.tv_toy_names);


// TODO (4) Use the static ToyBox.getToyNames method and store the names in a String array

String[] toyNames = ToyBox.getToyNames();


그런데 Excercise에서 작업을 하면 문제가 없으나

기존 프로젝트에서 작업하는 경우에는 ToyBox class가 없으므로 Error가 난다.

ToyBox라는 class를 만들거나 복사해 온다.

package com.example.nobang.favoritetoys;

public final class ToyBox {

    public static String[] getToyNames() {
        return new String[] {
                "Red Toy Wagon",
                "Chemistry Set",
               
                "Squirt Guns",
                "Miniature Replica Animals Stuffed with Beads that you swore to your parents would be worth lots of money one day",
                "Creepy Gremlin Doll",
                "Neodymium-Magnet Toy"
        };
    }


에러가 없으면 다음 Todo

// TODO (5) Loop through each toy and append the name to the TextView (add \n for spacing)

for (String toyName : toyNames) {
    mToysListTextView.append(toyName + "\n\n\n");
}


ToyBox class에 있는 장난감이름들을 불러와서

TextView에 일렬로 쭉(for문으로) 붙이는 거다.



todo 3을 진행하지 않으면 mToysListTextView가 초기화되어있지 않기 떄문에 아래와 같이 에러가 난다.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nobang.favoritetoys/com.example.nobang.favoritetoys.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference
 

MainActivity

- solution 프로젝트에는 TODO가 COMPLETED로 되어있음.

- todo를 진행했으면 COMPLETED로 바꿔주는 것이 좋음.

결과

"\n\n\n"으로 줄바꿈이 됨.


728x90

안드로이드 빌드를 했을 때

'Your project path contains non-ASCII characters' 같은 에러가 나오며 안될 때가 있다.


Your project path contains non-ASCII characters. This will most likely cause the build to fail on Windows. Please move your project to a different directory. See http://b.android.com/95744 for details. This warning can be disabled by adding the line 'android.overridePathCheck=true' to gradle.properties file in the project directory.
Open File
 

Open File을 누르면 build.gradle 파일이 열리는데

프로젝트의 경로가 영어가 아닐 때 발생하는 에러다.

(project path is not english. ex. Korean)


gradle.properties 파일에  com.android.build.gradle.overridePathCheck=true 를 추가 한다.


그리고는 try again 하면 된다.

728x90
BLOG main image
"그게 뭐 어쨌다는 거냐?" 늘 누가 나에게 나에대한 말을할 때면 이말을 기억해라. by nobang

카테고리

nobang이야기 (1933)
Life With Gopro (7)
Life With Mini (79)
Diary (971)
너 그거 아니(do you know) (162)
난 그래 (159)
Study (290)
속지말자 (10)
Project (34)
Poem (15)
Song (0)
Photo (113)
낙서장 (45)
일정 (0)
C.A.P.i (2)
PodCast (0)
nobang (27)
고한친구들 (4)
recieve (0)
History (0)
android_app (2)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

Total :
Today : Yesterday :