728x90
728x90

안드로이드 4대 컴포넌트

안드로이드 아키텍쳐에서 가장 중요한 요소. 4가지가 반드시 있어야하는건 아니지만
액티비티는 무조건 1개 이상 존재
해야한다. 나머지는 선택적이다.

 


 

액티비티 

화면을 구성하는 가장 기본적인 컴포넌트

public class MainActivity extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {

 

서비스 : 액티비티와 상관없이 백그라운드에서 동작하는 컴포넌트
서비스 생성 -> 서비스 시작 -> 서비스 종료

브로드캐스트 리시버 : 방송 수신. OS가 공지해주는 것. 배터리 방전, 문자메세지 도착, SD카드 탈부착, 네트워크 환경 변화 등이 발생하면 방송 신호를 보냄.

컨텐트 프로바이더 : 제공자. 응용프로그램 사이에 데이터(컨텐츠, 주로 글자)를 상호 공유하기 위한 컴포넌트. 콘텐트 프로바이더의 정보를 제공하는 방법으로는 URI가 있다. (Uniform Resource Identifier). 인텐트는 액티비티 사이를 연결한다.

양방향 액티비티 : 메인 액티비티에서 세컨드 액티비티로 데이터를 넘긴 후에 다시 메인 액티비티로 데이터를 돌려주는 경우. 보낼 때 putExtra(), 받을 때 getExtra()로 받는다. 주고받을 때 "" 안에다가 데이터형과 함께 보낸다.

 

 

액티비티 생명주기

액티비티의 생성부터 소멸까지의 주기. 
안드로이드는 화면이 작아 동시에 여러 개의 액티비티(화면)가 나올 수 없다.
앞의 화면 하나만 활성화된 상태이고 나머지는 모두 비활성화된 상태로 남게 된다.

 

 


 

인텐트

인텐트는 안드로이드 4개 컴포넌트가 상호 간에 데이터를 주고 받기 위한 메시지 객체다. 명시적 인텐트와 암시적 인텐트로 구분한다.

 

명시적 인덴트

다른 액티비티의 이름을 명확히 지정할 때 사용하는 방법
메인 액티비티에서 인텐트에 데이터를 실어서 넘긴 후 세컨드 액티비티에서 받은 데이터를 처리

 

 

암시적 인텐트 (Implicit Intent, 묵시적 인텐트)

약속된 Action을 지정하여 안드로이드에서 제공하는 기존 응용프로그램을 실행하는 것
전화 발신을 예를 들면 전화번호를 인텐트로 넘긴 후에 전화걸기 응용프로그램이 실행되는 것과 같다.

 

암시적 인텐트(Implicit Intent, 묵시적 인텐트) 911에 응급전화를 거는 형식
전화 걸기를 하려면 AndroidManifest.xml에 다음과 같이 권한을 추가해야 함

 


 

로그캣 : 작성중인 프로그램에 예기치 못한 오류가 발생했을 때 원인을 파악하는 방법 중 하나가 로그를 남기는 것이다.

 


 

실습하기

 

버튼을 누르면 새 화면이 열리는 예제 (액티비티 두 개 사용)

 

1. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="새 화면 열기"
    android:id="@+id/btnNewActivity" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="돌아가기"
        android:id="@+id/btnReturn" />
</LinearLayout>

 

 

2. MainActivity.java

package com.example.ex7_listchat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("메인 액티비티");

        Button btnNewActivity = (Button) findViewById(R.id.btnNewActivity);
        btnNewActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,
                        SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

 

 

3. 새로운 액티비티인 SecondActivity.java 파일을 만든다.

 

자바 코드에 액티비티의 필수 메소드인 onCreate()를 추가한 후 자동완성한다. second.xml을 화면에 보여주는 코드를 추가하고, second.xml의 <돌아가기>를 클릭하면 현재 액티비티를 끝내는 코드를 추가한다. SecondActivity는 메인 액티비티에서 호출할 것이므로 SecondActivity를 종료하면 다시 메인 액티비티가 나타난다. 메인 액티비티에서 SecondActivity를 호출하는 코드를 추가한다.

 

4. secondActivity.java

package com.example.ex7_listchat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        setTitle("Second 액티비티");

        Button btnReturn = (Button) findViewById(R.id.btnReturn);
        btnReturn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                finish();
            }
        });
    }
}

 

완성된 프로젝트를 실행하면 '프로젝트명'이 강제 중지되었다는 오류가 발생. 
안드로이드에서는 사용될 액티비티를 AndroidManifest.xml에 꼭 등록해야하며 메인 액티비티는 자동 등록되지만 추가한 SecondActivity는 별도로 등록해줘야 한다.

 

5. manifests > AndroidManifest.xml

파일에 SecondActivity를 등록해서 application 태그 안에 코딩한다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ex7_listchat">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SecondActivity"
            android:label="Second 액티비티"/>
    </application>
</manifest>

 

//xml
//xml

 


 

레이팅바 예제

 

activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <RatingBar
        android:id="@+id/ratingBar2"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="10"
        android:stepSize="1"/>
    <RatingBar
        android:id="@+id/ratingBar3"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:rating="1.5"/>
    <Button
        android:id="@+id/btnInc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="증가시키기"/>
    <Button
        android:id="@+id/btnDec"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="감소시키기"/>
</LinearLayout>

 

java

package com.example.chapter10;

import androidx.appcompat.app.AppCompatActivity;

import android.media.Rating;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RatingBar rating1, rating2, rating3;
        Button btnInc, btnDec;

        rating1 = (RatingBar) findViewById(R.id.ratingBar1);
        rating2 = (RatingBar) findViewById(R.id.ratingBar2);
        rating3 = (RatingBar) findViewById(R.id.ratingBar3);
        btnInc = (Button) findViewById(R.id.btnInc);
        btnDec = (Button) findViewById(R.id.btnDec);

        btnInc.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                rating1.setRating(rating1.getRating()+rating1.getStepSize());
                rating2.setRating(rating2.getRating()+rating2.getStepSize());
                rating3.setRating(rating3.getRating()+rating3.getStepSize());
            }
        });
        btnDec.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                rating1.setRating(rating1.getRating()-rating1.getStepSize());
                rating2.setRating(rating2.getRating()-rating2.getStepSize());
                rating3.setRating(rating3.getRating()-rating3.getStepSize());
            }
        });
    }
}

 


 

실습 10-2 명화 선호도 투표 앱 만들기

 

 

activity_main.xml 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <ImageView
            android:id="@+id/iv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic1" />

        <ImageView
            android:id="@+id/iv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic2" />

        <ImageView
            android:id="@+id/iv3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic3" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">

        <ImageView
            android:id="@+id/iv4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic4" />

        <ImageView
            android:id="@+id/iv5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic5" />

        <ImageView
            android:id="@+id/iv6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic6" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3">
        <ImageView
            android:id="@+id/iv7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic7"/>
        <ImageView
            android:id="@+id/iv8"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic8"/>
        <ImageView
            android:id="@+id/iv9"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/pic9"/>
    </LinearLayout>

    <Button
        android:id="@+id/btnResult"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="투표 종료"/>

</LinearLayout>

 

메인 액티비티에서 사용할 activity_main.xml 수정

-  바깥 리니어레이아웃 안에 리니어레이아웃 3, 버튼 1개를 생성 
-  layout_weight 3:3:3:1 
-  3개의 레이아웃에는 각각 3개의 이미지 뷰를 넣고 layout_weigh 1:1:1 
- 필요하면 이미지뷰에 적당한 layout_margin(ex : 5dp) 
- 9 이미지뷰의 id iv1~iv9, 버튼의 id btnResult로 함

 

MainActivity.java

package com.example.chapter10_9;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("명화 선호도 투표");

        final int voteCount[] = new int[9];
        for(int i=0; i<9; i++) {
            voteCount[i] = 0;
            //9개의 이미지 버튼 객체배열
        }
        ImageView image[] = new ImageView[9];
            // 9개의 이미지버튼 ID 배열

        Integer imageId[] = { R.id.iv1, R.id.iv2, R.id.iv3, R.id.iv4,
                    R.id.iv5, R.id.iv6, R.id.iv7, R.id.iv8, R.id.iv9 };

        final String imgName[] = { "독서하는 소녀", "꽃장식 모자 소녀", "부채를 든 소녀",
            "이레느깡 단 베르양", "잠자는 소녀", "테라스의 두 자매", "피아노 레슨",
            "피아노 앞의 소녀들", "해변에서"};

        for (int i = 0; i<imageId.length; i++){
            final int index;
            index = i;
            image[index] = (ImageView) findViewById(imageId[index]);
            image[index].setOnClickListener(new View.OnClickListener(){
                public void onClick(View v) {
                    //투표수 증가
                    voteCount[index]++;
                    Toast.makeText(getApplicationContext(),
                            imgName[index]+": 총"+ voteCount[index] +" 표",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        Button btnFinish = (Button) findViewById(R.id.btnResult);
        btnFinish.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
                intent.putExtra("VoteCount", voteCount);
                intent.putExtra("ImageName", imgName);
                startActivity(intent);
            }
        });
    }
}

 

 

result.xml

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

    <TableRow>
        <TextView
            android:id="@+id/tv1"
            android:layout_gravity="center_vertical"
            android:text="그림1"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar1"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv2"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar2"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv3"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar3"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv4"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar4"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv5"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar5"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv6"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar6"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv7"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar7"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv8"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar8"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/tv9"
            android:layout_gravity="center_vertical"
            android:text="그림2"
            android:textSize="15dp"/>
        <RatingBar
            android:id="@+id/rbar9"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">
        </RatingBar>
    </TableRow>
    <TableRow>
        <Button
            android:id="@+id/btnReturn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:text="돌아가기"/>
    </TableRow>
</TableLayout>

 

* 서브 액티비티에서 사용할 result.xml /res/layout 폴더에 생성

바깥은 테이블레이아웃으로 설정
stretchColumns 속성을 0으로 함
<TableRow>를 그림의 숫자와 동일한 (9+1)개로 하고, 각 테이블 로우에는 텍스트뷰 1, 래이팅바 1개를 생성
마지막 테이블 로우에는 <돌아가기> 생성
텍스트뷰의 id tv1~tv9, 래이팅바의 id rbar1~rbar9, 버튼의 id btnReturn으로 함

 

ResultActivity.java

package com.example.chapter10_9;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class ResultActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        setTitle("투표 결과");

        //앞 화면에서 보낸 투표 결과 값을 받는다.
        Intent intent = getIntent();
        int[] voteResult = intent.getIntArrayExtra("VoteCount");
        String[] imageName = intent.getStringArrayExtra("ImageName");

        //9개의 TextView, Rating Bar 객체배열
        TextView tv[] = new TextView[imageName.length];
        RatingBar rbar[] = new RatingBar[imageName.length];

        //9개의 TextView, Rating Bar ID 배열
        Integer tvID[] = { R.id.tv1, R.id.tv2, R.id.tv3,
                R.id.tv4, R.id.tv5, R.id.tv6, R.id.tv7, R.id.tv8, R.id.tv9 };
        Integer rbarID[] = { R.id.rbar1, R.id.rbar2, R.id.rbar3,
                R.id.rbar4, R.id.rbar5, R.id.rbar6, R.id.rbar7, R.id.rbar8, R.id.rbar9 };

        for (int i = 0; i<voteResult.length; i++){
            tv[i] = (TextView) findViewById(tvID[i]);
            rbar[i] = (RatingBar) findViewById(rbarID[i]);
        }

        //각 TextView 및 RatingBar 에 넘겨 받은값을 반영
        for (int i=0; i<voteResult.length; i++){
            tv[i].setText(imageName[i]);
            rbar[i].setRating((float)voteResult[i]);
        }

        Button btnReturn = (Button) findViewById(R.id.btnReturn);
        btnReturn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                finish();
            }
        });
    }
}

 

* Java 코드 작성 및 수정

새로운 액티비티인 ResultActivity.java 파일을 만듦
onCreate( ) 메소드를 추가한  setContentView(R.layout.result) 추가
AndroidManifest.xml에 등록

* onCreate() 내부에 필요한 변수 선언

그림을 클릭할 때마다 투표 수를 저장할 9개짜리 배열을 선언하고 0으로 초기화
이미지뷰 위젯을 저장할 9개짜리 배열을 선언
이미지뷰 위젯의 id R.id.iv1 ~ iv9  저장한 배열을 선언
그림의 이름을 저장한 9개짜리 배열 선언

* onCreate() 내에 이미지 클릭 시 동작할 내용 코딩
 이미지뷰에 대해 클릭 이벤트 리스너 생성 
이미지뷰가 9개이므로 반복문을 사용
이미지 클릭하면 각 이미지의 투표수가 증가하도록 설정
이미지 클릭할 때마다 해당 이미지 이름과 누적된 투표수도 토스트 메시지로 보여줌

* onCreate() 내에 <투표 종료>에 대해서 클릭 이벤트 리스너 생성
인텐트를 생성, 인텐트에 투표수 배열과 그림 이름 배열을 넣은  결과 액티비티 호출

 

AndroidManifest.xml 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chapter10_9">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".ResultActivity"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

* 서브 액티비티인 ResultActivity.java 파일의 onCreate( ) 메소드 안을 코딩
- 메인 액티비티에서 보낸 인텐트 받고넘겨 받은 투표 결과 배열과 그림 이름 배열 저장

* 서브 액티비티 나머지 코딩
- 
result.xml 텍스트뷰 9개와 래이팅바 9개의 위젯 변수 배열을 선언

* 텍스트뷰 id를 저장한 배열 변수래이팅바의 id를 저장한 배열 변수를 선언

* XML 파일의 텍스트뷰  래이팅바를 위젯 변수에 대입

* 텍스트뷰 위젯 변수에 넘겨받은 그림 이름을 적용

* 래이팅바에는 넘겨받은 투표 결과를 적용

* 버튼을 클릭하면 서브 액티비티를 종료 -> , 메인 액티비티로 돌아간다.

 

 

//activity_result.xml 수정

<TableRow>
	<TextView
    	android:id="@+id/tvTop"
        android:text="1등"
        android:textSize="15sp"
        android:layout_gravity="center"
		android:layout_span="2"
        />
</TableRow>
<TableRow>
	<ImageView
    	android:id="@+id/ivTop"
		android:layout_span="2"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/pic1"
        android:scaleType="fitCenter"
        />
</TableRow>

...

//레이팅바를 작은 모델로 만드는 것은 design탭에서 바꾸면 편하다.

 

//ResultActivity.java 수정 - 가장 많이 받은 득표의 그림을 보여준다.
//max값은 0으로 잡아 비교하는 알고리즘

..

int[] voteResult = intent.getIntArrayExtra("VoteCount");
String imageName = intent.getStringtArrayExtra("ImageName");

Integer imageField[] = R.drawable.pic1, R.drawable.pic2,
						R.drawable.pic3, R.drawable.pic4, R.drawable.pic5,
						R.drawable.pic6, R.drawable.pic7, R.drawable.pic8,
						R.drawable.pic9 };

TextView tvTop = (TextView)findViewById(R.id.tvTop);
ImageView ivTop = (ImageView)findViewById(R.id.ivTop);

//투표수가 최대인 것
int max_index=0;
for(int i=0; i<voteResult.lenght; ++i)
	{
    //가장 큰값의 번지를 구하게 된다.
	if( voteResult[max_index] < voteResult[i] )
    	max_index = i;
	}
tvTop.setText(imageName[max_index]);
ivTop.setImageResource(imageFiled[max_index]);

//9개의 TextView, RatingBar 객체배열
TextView tv[] = new TextView[imageName.length];

..

 

 


 

양방향 데이터 전달 예제


메인 액티비티의 에디트텍스트의 두 수를 세컨드 액티비티에서더한 후에 다시 메인 액티비티로 돌려준다.

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edtNum1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/edtNum2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/btnNewActivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="더하기"/>

</LinearLayout>

 

MainActivity.java

package com.example.chapter10_16;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("메인 액티비티");

        Button btnNewActivity = (Button) findViewById(R.id.btnNewActivity);
        btnNewActivity.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                EditText edtNum1 = (EditText) findViewById(R.id.edtNum1);
                EditText edtNum2 = (EditText) findViewById(R.id.edtNum2);

                Intent intent = new Intent(getApplicationContext(),
                        SecondActivity.class);
                intent.putExtra("Num1",
                        Integer.parseInt(edtNum1.getText().toString()));
                intent.putExtra("Num2",
                        Integer.parseInt(edtNum2.getText().toString()));
                startActivityForResult(intent, 0);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode==RESULT_OK) {
            int hap = data.getIntExtra("Hap", 0);
            Toast.makeText(getApplicationContext(), "합계:" + hap,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

 

second.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <Button
        android:id="@+id/btnReturn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="돌아가기"/>

</LinearLayout>

 

SecondActivity.java

package com.example.chapter10_16;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        setTitle("Second 액티비티");
        Intent inIntent = getIntent();
        final int hapValue = inIntent.getIntExtra("Num1", 0) +
                inIntent.getIntExtra("Num2", 0);

        Button btnReturn = (Button) findViewById(R.id.btnReturn);
        btnReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent outIntent = new Intent(getApplicationContext(), 
                        MainActivity.class);
                outIntent.putExtra("Hap", hapValue);
                setResult(RESULT_OK, outIntent);
                finish();
            }
        });
    }
}

 

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chapter10_16">
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SecondActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 


 

암시적 인텐트 예제

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnDial"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="전화 걸기"/>
    <Button
        android:id="@+id/btnWeb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="홈페이지 열기"/>
    <Button
        android:id="@+id/btnGoogle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="구글맵 열기"/>
    <Button
        android:id="@+id/btnSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="구글 검색하기"/>
    <Button
        android:id="@+id/btnSms"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="문자 보내기"/>
    <Button
        android:id="@+id/btnPhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="사진 보기"/>
</LinearLayout>

 

MainActivity.java

package com.example.chapter10_20;

import androidx.appcompat.app.AppCompatActivity;

import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("암시적 인텐트 예제");

        Button btnDial = (Button) findViewById(R.id.btnDial);
        Button btnWeb = (Button) findViewById(R.id.btnWeb);
        Button btnGoogle = (Button) findViewById(R.id.btnGoogle);
        Button btnSearch = (Button) findViewById(R.id.btnSearch);
        Button btnSms = (Button) findViewById(R.id.btnSms);
        Button btnPhoto = (Button) findViewById(R.id.btnPhoto);

        btnDial.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("tel: 010-1234-5678");
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
            }
        });

        btnWeb.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("http://www.naver.com");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        btnGoogle.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Uri uri = Uri.parse("geo:37.5543,126.9135");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        btnSearch.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                intent.putExtra(SearchManager.QUERY, "안드로이드");
                startActivity(intent);
            }
        });

        btnSms.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.putExtra("sms_body", "안녕하세요?");
                intent.setType("vnd.android-dir/mms-sms");
                startActivity(intent);
            }
        });

        btnPhoto.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.fromFile(new File("/sdcard/jeju13.jpg"));
                intent.setDataAndType(uri, "image/jpeg");
                startActivity(intent);
            }
        });
    }
}

 

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.chapter10_20">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

View > Tool Windows > Device File Explorer

 


 

로그캣 예제

//xml
//xml

android.util.log.i ("") 부분에 공백을 적으면 안된다. (10-24)

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v