Develop/Android

[Android] Fragment 적용 방법

안다희 2019. 1. 8. 12:40
728x90


1. fragment를 넣고 싶은 xml에 다음 코드 추가

activity_search.xml

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@id/btn_back">

</FrameLayout> 




2. fragment안에 들어가는 xml 파일 생성

=> fragment_search.xml



3. SearchFragment.java 생성



import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; //이걸로 import
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class SearchResultFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_search, container, false);
return rootView;
}

} 



4. SearchActivity.java 다음 코드 추가

SearchResultFragment searchResultFragment = new SearchResultFragment();

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, searchResultFragment).commit(); 




빨간 글씨 파란 글씨만 주의하면 ok!!

출처: https://mingos-habitat.tistory.com/34 [밍고의서식지:티스토리]