[Android] 안드로이드 앱에 버튼(Button) 추가

[Android] 안드로이드 앱에 버튼(Button) 추가

1. Activity 레이아웃 XML에 버튼(Button) 태그를 추가한다.

예를 들어 activity_main.xml 에 아래 내용을 추가한다.

<Button
    android:id=”@+id/button1″
    android:layout_width=”match_parent”
    android:layout_height=”wrap_content”
    android:text=”Button1″
    app:layout_constraintStart_toStartOf=”parent”
    app:layout_constraintTop_toTopOf=”parent” />

    <Button
    android:id=”@+id/button2″
    android:layout_width=”match_parent”
    android:layout_height=”wrap_content”
    android:layout_marginTop=”48dp”
    android:text=”Button2″
    app:layout_constraintStart_toStartOf=”parent”
    app:layout_constraintTop_toTopOf=”parent” />

2. 만약 버튼(Button) 태그에 빨간색 밑줄이 그어지면서 “This view is not constrained vertically: at runtime it will jump to the top unless you add a vertical constraint more… (Ctrl+F1)” 오류가 발생하는 경우.

Activity 레이아웃 xml(예를 들어 activity_main.xml 파일) 하단의 [Design] 탭을 클릭 – 상단의 마법봉 모양 아이콘(Infer Constraints) 버튼을 클릭한다.

3. Activity 자바 파일의 onCreate 메서드를 찾는다.

그 안에 findViewById 메서드로 버튼 변수를 선언하고, 이어서 온클릭 리스너(OnClickListener)를 구현한다.

아래 코드처럼 쓰고 “// 내용” 부분에 버튼 클릭 시 발생할 이벤트를 작성하면 된다.

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

        Button button1 = (Button) findViewById(R.id.button1);
        Button button2 = (Button) findViewById(R.id.button2);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 내용
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 내용
            }
        });
    }

참고사이트 : https://recipes4dev.tistory.com/54