활동 그룹 내에서 다른 조각으로 조각 바꾸기


137

그룹 활동 안에 조각이 있는데 다른 조각으로 바꾸고 싶습니다.

FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

액티비티 그룹을 사용하지 않고 별도의 프로젝트로 수행하면 제대로 작동합니다. 제어가 getview () 내부로 이동하면 로그 고양이에서 모든 것이 잘 작동하지만 아무런보기도 보이지 않으며 예외가 발생하지 않습니다. 섹션 세부 조각으로 대체됩니다.

책 세부 조각의 Xml에는 ID book_description_fragment가 있고 섹션 설명 조각에 대한 xml에는 section_description_fragment가 있습니다.

위의 코드는 항목의 onClick 메서드에 있으며 사용자가 가로 스크롤보기에서 항목을 탭하면 조각이 변경되기를 원합니다.

답변:


250

XML로 하드 코딩 된 단편은 대체 할 수 없습니다. 프래그먼트를 다른 프래그먼트로 교체해야하는 경우 우선 동적으로 추가해야합니다.

참고 : R.id.fragment_container 는 조각을 가져올 활동에서 선택한 레이아웃 또는 컨테이너입니다.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

8
이 경우 R.id.fragment_container는 무엇입니까?
Guy

4
@Guy, 조각을로드하려는 모든 레이아웃이 될 수 있습니다.
Subin Sebastian

1
xml 파일에서 조각의 이름은 무엇입니까? 조각을 동적으로 추가하고 정적 조각을 원하지 않습니다.
Rajat Mehra 2016 년

1
@RajatMehra 프래그먼트를 동적으로 추가하려면 XML 내부에 프래그먼트를 전혀 지정할 필요가 없습니다. 컨테이너보기를 사용할 수 있습니다. 답을 다시 읽으십시오.
Subin Sebastian

4
@Ahmed 그 이유는 아키텍처에 따라 시스템이 모든 <fragment> 태그를 해당 조각이 제공하는보기 (그룹)로 교체하기 때문 onCreateView()입니다. 따라서 예상 할 수 있듯이 조각에 대한 참조는 실제로 뷰 수준에서 손실됩니다. 따라서 기본적으로 조각을 바꿀 수는 없지만 컨테이너에 현재있는보기를 수동으로 제거하고 필요한 경우 조각을 대신 배치 할 수 있습니다.
Subin Sebastian

35

질문을 참조하십시오

" 동적으로 추가 된 조각 " 만 바꿀 수 있습니다 .

따라서 동적 조각을 추가하려면 예제를 참조하십시오 .


1
안녕하세요 . 해결책을 찾았습니다. 실제로 조각의 내용을 레이아웃에 배치하지 않고 이전 조각의 내용에 다른 조각을 사용하고있었습니다
Lion Heart

아니요, 여기서 전체 조각을 새 조각으로 바꾸려고했습니다.
Sana

1
@ 라이온 하트, 찾은 솔루션을 자세히 설명해 주시겠습니까?
Namratha

링크가 죽었다 : /
Neon Warge

8

조각 교체수명주기 를 관리하는 완벽한 방법 으로 요지를 만들었습니다 .

현재 프래그먼트가 동일하지 않고 백 스택에 있지 않은 경우 (이 경우 팝이 됨) 현재 프래그먼트를 새 프래그먼트로만 바꿉니다.

조각을 백 스택에 저장하는 것처럼 여러 옵션이 포함되어 있습니다.

=> 여기 요점 참조

이 활동과 단일 활동을 사용하여이를 활동에 추가 할 수 있습니다.

@Override
public void onBackPressed() {
    int fragments = getSupportFragmentManager().getBackStackEntryCount();
    if (fragments == 1) {
            finish();
            return;
    }

    super.onBackPressed();
}

1
@ RémiP 링크가 예상대로 작동합니다. 더 나은 IMO를 확인할
Hugo Gresse

8

android.support.v4에서 아래 코드를 사용하십시오.

FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();

4

v4를 사용하여이 코드를 사용하십시오.

 ExampleFragment newFragment = new ExampleFragment();     
 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  
 // Replace whatever is in the fragment_container view with this fragment,  
 // and add the transaction to the back stack so the user can navigate back   
 transaction.replace(R.id.container, newFragment);
 transaction.addToBackStack(null);  
 // Commit the transaction   
 transaction.commit();

3

당신이 잘하고 있기를 바랍니다. 작업을 시작했을 때도 Android Fragments같은 문제가 발생했습니다 .1- 다른 것과 조각을 전환하는 방법에 대해 읽었습니다. 2- 프래그먼트 Fragment container가없는 경우 프래그먼트를 추가하는 방법 .

그런 다음 R & D 후, 지금까지 많은 프로젝트에서 도움이되는 기능을 만들었으며 여전히이 간단한 기능을 사용하고 있습니다.

public void switchFragment(BaseFragment baseFragment) {
    try {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
        if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
            ft.add(R.id.home_frame, baseFragment);
        } else {
            ft.replace(R.id.home_frame, baseFragment);
        }
        ft.addToBackStack(null);
        ft.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

코드 시간을 즐기십시오 :)


3

ViewPager를 사용하십시오. 그것은 나를 위해 일하고 있습니다.

final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager); 
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        viewPager.setCurrentItem(1);
    }
});

1

이 코드를 사용할 수 있습니다

((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();

이 코드를 사용할 수 있습니까

YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);

        if (fragments==null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
        }

0

kotlin에서는 다음을 수행 할 수 있습니다.

// instantiate the new fragment
val fragment: Fragment = ExampleFragment()

val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()

0

트랜잭션에 간단한 코드를 사용할 수 있습니다.

Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit(); 

0

동적으로 한 줄의 코드에서 나는 변화 조각
그것은 어떤 SDK 버전과 androidx의 작품입니다
I 사용 탐색 등BottomNavigationView

    BottomNavigationView btn_nav;
    FragmentFirst fragmentFirst;
    FragmentSecond fragmentSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        fragmentFirst = new FragmentFirst();
        fragmentSecond = new FragmentSecond ();
        changeFragment(fragmentFirst); // at first time load the fragmentFirst
        btn_nav = findViewById(R.id.bottomNav);
        btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()){
                    case R.id.menu_first_frag:
                        changeFragment(fragmentFirst); // change fragmentFirst
                        break;
                    case R.id.menu_second_frag:
                        changeFragment(fragmentSecond); // change fragmentSecond
                        break;
                        default:
                            Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }
public void changeFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
    }
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.