반응형
Layout Inflater는 레이아웃을 객체화 시켜주는 작업이다.
이 때 객체화 과정은 runtime 때 이루어진다. 이 Inflater를 이용해 부분 화면을 설계할 수 있다.
LinearLayout container; // container view 추가.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
container = findViewById(R.id.container);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.sub1, container, true);
CheckBox checkBox = container.findViewById(R.id.checkBox);
checkBox.setText("Loading Complete.");
}
});
}
여기서 LayoutInflater 객체를 만들 때는 이것이 시스템 서비스로 제공하는 클래스 이므로 getSystemService를 이용해 객체를 만들어준다.
inflator.inflate()는 3개의 매개변수를 가진다. 컴파일러에서 가져와보면
첫번째 인자로는 부분화면이 될 xml이 들어가고, 두번째로는 부분화면의 부모 레이아웃이 될 객체가 들어간다.
여기서는 위에서 LinearLayout container = findViewById(R.id.container)가 된다. 세번째 인자로는 객체를 붙일지 안붙일지 결정하는 건데 붙이면 화면에 보이고 안붙이면 안보인다.
이렇게 inflate된 부분 레이아웃에 다른 뷰를 사용하려면 class에서 멤버접근하듯이 해야된다.
위 코드 블럭에서 만들어진 checkBox는 지금 메인 액티비티에서의 뷰가 아니라 sub1.xml의 뷰이다. 그리고 sub1.xml은 inflate과정을 통해 container로 객체화 되었다.
따라서 container.findViewById()처럼 객체에 대한 멤버를 참조하는 방식을 택해야 사용가능하다.
https://developer.android.com/reference/android/view/LayoutInflater#inflate(int,%20android.view.ViewGroup,%20boolean)
"댓글, 공감 버튼 한 번씩 누르고 가주시면 큰 힘이 됩니다"
반응형