본문 바로가기
computing

20250911_android_2

by greentworkshop 2025. 9. 11.

교재 20p

프로젝트 계층도

//확장자 MainActivity.java



package com.example.project0911;

import androidx.appcompat.app.AppCompatActivity;


import android.widget.Button;  // 추가해야 함
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.graphics.Color;  // Color 클래스를 사용해야 함


public class MainActivity extends AppCompatActivity {
    Button button1, button2, button3;//**p**
    LinearLayout baseLayout;  // LinearLayout을 참조하기 위한 변수 추가

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

        button1=(Button)findViewById(R.id.Btn01);//**p**Button -> Btn01
        // Button button1=(Button)findViewById(R.id.Btn01); 선언 안하고 이렇게도 가능
        button1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),
                        "버튼을 눌렀군요", Toast.LENGTH_SHORT).show();//**p**
                baseLayout.setBackgroundColor(Color.GREEN);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button2.setText("안녕하세요? 반갑습니다!"); // 텍스트 변경
            }
        });

        // button3 클릭 시 배경색을 Magenta로 변경
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button3.setBackgroundColor(Color.MAGENTA); // 배경색 변경
            }
        });
       // button2=(Button)findViewById(R.id.Btn02);//**p**Button -> Btn01

       //button3=(Button)findViewById(R.id.Btn03);//**p**Button -> Btn01

    } //onCreate()
} //Activity()
//확장자 main01.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff00"
    android:id="@+id/baseLayout"
        >


<!--아래 wrap을 match로 바꾸면 화면 전체를 채움-->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Btn01"
            android:text="@string/strBtn1"
            android:textSize="30dp"
            ></Button>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/Btn02"
                    android:text="@string/strBtn2"
                    android:textSize="30dp"
                    ></Button>

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/Btn03"
                    android:text="@string/strBtn3"
                    android:textSize="30dp"
                    ></Button>


        </LinearLayout>

        <!--ctrl space -> 입력 가능한 명령어 나열-->
<!-- android:id="@+id/버튼이름"-->
    <!-- android:text="@string/strBtn1"
    value 하위폴더의 strings.xml파일에     <string name="strBtn1">버튼입니다......</string> 작성
    -->

위 코드처럼 만들면 에뮬레이터에서 동작이 안되는 문제 발견

package com.example.project0911;

import androidx.appcompat.app.AppCompatActivity;

import android.widget.Button;  // 추가해야 함
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.LinearLayout;
import android.graphics.Color;  // Color 클래스를 사용해야 함

public class MainActivity extends AppCompatActivity {
    Button button1, button2, button3; // 버튼 변수 선언
    LinearLayout baseLayout;  // LinearLayout을 참조하기 위한 변수 추가

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

        // 버튼 초기화
        button1 = (Button) findViewById(R.id.Btn01);
        button2 = (Button) findViewById(R.id.Btn02); // button2 초기화 추가
        button3 = (Button) findViewById(R.id.Btn03); // button3 초기화 추가
        baseLayout = (LinearLayout) findViewById(R.id.baseLayout); // baseLayout 초기화

        // button1 클릭 시 Toast와 배경색 변경
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),
                        "버튼을 눌렀군요", Toast.LENGTH_SHORT).show();
                baseLayout.setBackgroundColor(Color.GREEN);  // 배경색 변경
            }
        });

        // button2 클릭 시 텍스트 변경
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button2.setText("안녕하세요? 반갑습니다!"); // 텍스트 변경
            }
        });

        // button3 클릭 시 배경색을 Magenta로 변경
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                button3.setBackgroundColor(Color.MAGENTA); // 배경색 변경
            }
        });
    } // onCreate()
} // MainActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffff00"
    android:id="@+id/baseLayout">

        <!-- Button 1 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Btn01"
            android:text="@string/strBtn1"
            android:textSize="30sp" /> <!-- sp로 수정 -->

        <!-- Button 2 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Btn02"
            android:text="@string/strBtn2"
            android:textSize="30sp" /> <!-- sp로 수정 -->

        <!-- Button 3 -->
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/Btn03"
            android:text="@string/strBtn3"
            android:textSize="30sp" /> <!-- sp로 수정 -->

</LinearLayout>


    <!--ctrl space -> 입력 가능한 명령어 나열-->
<!-- android:id="@+id/버튼이름"-->
    <!-- android:text="@string/strBtn1"
    value 하위폴더의 strings.xml파일에     <string name="strBtn1">버튼입니다......</string> 작성
    -->

button2와 button3에 대한 초기화가 없어서 오류 발생

이로 인해 NullPointerException이 발생하고, 앱이 중단

 

해결방안

 

  • findViewById()로 button2와 button3 초기화: button2와 button3도 findViewById()로 초기화해야 한다.
  • textSize에서 dp 대신 sp 사용: 이전에 언급한 대로 textSize에는 sp 단위를 사용해야 하므로 이를 수정할 필요가 있다.

수정 사항 

  1. button2와 button3의 초기화 추가: button1과 동일하게 findViewById()를 사용하여 button2와 button3을 초기화. 이를 통해 버튼을 클릭했을 때 관련 동작이 정상적으로 실행됨.
  2. baseLayout 초기화: baseLayout을 초기화하여 배경색 변경을 할 수 있도록 했음.
  3. textSize: dp 대신 sp 단위를 사용하여 텍스트 크기를 지정했습니다. 이는 화면 크기와 무관하게 텍스트의 가독성을 보장하기 위해 중요함.

에뮬레이터에서 발생할 수 있는 오류 해결:

  1. NullPointerException: button2와 button3이 초기화되지 않으면 NullPointerException이 발생합니다. 이 문제를 해결하려면 위 코드와 같이 반드시 버튼을 초기화해야함.
  2. 리소스 문제: strings.xml 파일에서 strBtn1, strBtn2, strBtn3 문자열이 정의되어 있어야 함. 예를 들어, res/values/strings.xml 파일에 다음과 같은 문자열 정의가 필요:
<resources>
    <string name="strBtn1">버튼 1</string>
    <string name="strBtn2">버튼 2</string>
    <string name="strBtn3">버튼 3</string>
</resources>

 

 

'computing' 카테고리의 다른 글

20250916_네트워크보안_3  (1) 2025.09.16
20250915_iOS_3  (0) 2025.09.15
20250908_iOS_2  (0) 2025.09.08
20250904_안드로이드_1  (0) 2025.09.04
20250901 - iOS_1  (0) 2025.09.01