티스토리 뷰

다중 화면 처리

activity_main.xml

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

    <Button
        android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="NEXT" />

</LinearLayout>

 

activity_next.xml

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp"
    android:background="#CAE3ED" >

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BACK" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="반가워요!"
        android:textSize="30sp"
        android:gravity="center_horizontal" />

</LinearLayout>


MainActivity.java

  • (LinearLayout) 캐스케이딩: getLayoutInflater().inflate();는 View 형식 반환이므로 LinearLayout으로 변환
package com.example.test;

import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout d1 = (LinearLayout)getLayoutInflater().inflate(R.layout.activity_main, null);
        LinearLayout d2 = (LinearLayout)getLayoutInflater().inflate(R.layout.activity_next, null);

        setContentView(d1);

        Button n = d1.findViewById(R.id.next);
        n.setOnClickListener(v -> {setContentView(d2);});
        Button b = d2.findViewById(R.id.back);
        b.setOnClickListener(v -> {setContentView(d1);});
    }
}

실행 화면

공지사항
링크