이번 포스팅은 Activity를 만들거나 Fragment를 만들 때 더 이상 setContentView함수를 사용하거나 onCreateView를 override하지 않고 layout을 추가하는 방법에 대해 소개 합니다.

Activity

프로젝트를 만들면 처음 보이는 MainActivity는 이렇게 생겼습니다.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

하지만 androidx.appcompat:appcompat 라이브러리 버전이 1.1.0 이상 이라면 AppCompatActivity 생성자에 layoutId를 넘겨서 추가 할 수 있습니다.

class MainActivity : AppCompatActivity(R.layout.activity_main)

이렇게 할 수 있는 이유는 AppCompatActivity의 부모인 FragmentActivity의 부모인 ComponentActivity에서 mContentLayoutId로 우리가 생성자로 전달한 layoutId를 저장하고 있습니다.

@ContentView
public ComponentActivity(@LayoutRes int contentLayoutId) {
    this();
    mContentLayoutId = contentLayoutId;
}

그리고 ComponentActivity#onCreate 에서 setContentView를 호출하고 있습니다.

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSavedStateRegistryController.performRestore(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
    if (mContentLayoutId != 0) {
        setContentView(mContentLayoutId);
    }
}

그래서 앞으로 androidx.appcompat:appcompat 라이브러리 버전이 1.1.0 이상 이라면 더이상 setContentView를 사용하지 않고 생성자로 layoutId를 전달 함으로 써 Activity에 layout을 추가할 수 있습니다.

Fragment

보통 Fragment를 만들 때 onCreateView를 override해서 View를 리턴합니다.

class MainFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

}