IT story

Android-조각 ID 설정

hot-time 2020. 8. 6. 07:53
반응형

Android-조각 ID 설정


어떻게 설정할 수 있습니다 Fragment이야 ' Id내가 사용할 수 있도록 getSupportFragmentManager().findFragmentById(R.id.--)?


프로그래밍 방식으로 조각의 ID를 설정할 수 없습니다 .

그러나 String tagFragmentTransaction 내부에 Fragment를 고유하게 식별하는 데 사용할 수있는 설정이 있습니다.

Aleksey가 지적했듯이 ID를 FragmentTransactionadd(int, Fragment)메소드에 전달할 수 있습니다 . 그러나 이것은 조각의 ID를 지정하지 않습니다. ViewGroup에 삽입 할 의 ID를 지정합니다 Fragment. 이것은 Fragments를 고유하게 식별하지 않고 s 하기 때문에 내가 기대하는 목적에 유용하지 않습니다 ViewGroup. 이 ID는 하나 이상의 조각을 동적으로 추가 할 수있는 컨테이너 입니다 . 이러한 방법을 사용하여를 식별 하려면 삽입 할 때마다 레이아웃에 동적으로를 추가해야합니다 . 꽤 번거로울 것입니다.FragmentViewGroupFragment

따라서 귀하의 질문이 동적으로 추가하는 Fragment에 대한 고유 식별자를 만드는 방법이라면 FragmentTransaction' add (int containerViewId, Fragment fragment, String tag) 메소드와 FragmentManager's findFragmentByTag (String) 메소드 를 사용하는 것이 답입니다 .

내 앱 중 하나에서 문자열을 동적으로 생성해야했습니다. 그러나 어쨌든 실제 FragmentTransaction에 비해 그렇게 비싸지는 않습니다.

태그 방법의 또 다른 장점은 UI에 추가되지 않은 조각을 식별 할 수 있다는 것입니다. FragmentTransaction의 add (Fragment, String) 메소드를 참조하십시오 . Fragment의 필요가 없습니다 View! 구성 변경 사이에 일시적인 상태를 유지하는 데에도 사용할 수 있습니다!


조각 ID를 알 필요가 없습니다.

문서에서 :

public abstract Fragment findFragmentById (int id)

Finds a fragment that was identified by the given id either
when inflated from XML or as the container ID when added in
a transaction.

중요한 부분은 "트랜잭션에 추가 될 때 컨테이너 ID로"입니다.

그래서:

getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.fragment_holder, new AwesomeFragment())
    .commit();

그리고

AwesomeFragment awesome = (AwesomeFragment)
     getSupportFragmentManager()
          .findFragmentById(R.id.fragment_holder);

R.id.fragment_holder에서 보유하고있는 (굉장한) 조각을 얻을 수 있습니다.


대부분의 경우 조각 태그와 ID를 사용할 수 있습니다.
에서 태그 값을 설정할 수 있습니다 FragmentTransaction.add(Fragment fragment, String tag );. 그런 다음 명령 FragmentManager.findFragmentByTag(String tab)사용하여 문제의 조각을 찾을 수 있습니다 .


Tom과 다른 사람들이 이미 언급했듯이 조각에 태그를 넣고 해당 태그를 식별에 사용하는 방법이 있습니다. 그 해결책으로 겪은 후속 문제는 조각이 Activity (또는 실제로)와 연관 될 때까지 태그를 얻지 못한다는 것 FragmentManager입니다. 조각을 태그하기 전에 조각을 식별해야하는 경우 어떻게해야합니까?

내 솔루션은 지금까지 세계에서 가장 오래된 (Java) 트릭을 사용합니다. 생성자 중 하나에서 ID를 가져 와서 해당 ID getFragmentId()를 반환 하는 메소드를 제공하는 최소한의 템플릿 조각을 만듭니다 . 그런 다음 조기 식별이 필요한 조각이 해당 템플릿을 확장하고; 짜잔! 문제 해결됨.

이 솔루션의 힘은, 불행하게도, 템플릿 조각, 각 조각 유형에 대한 하나의 세트 필요 ListFragment, DialogFragment또는 오래된 일반 Fragment조기 발견이 필요합니다 (POFO를?!). 그러나 이것은 제공된 이익을 고려하여 내가 생각하는 조각의 경우 관리 할 수 ​​있습니다.

치유 상처를 찢어 미안 :-)

건배!


다음을 사용하십시오.

조각을 추가하려면

getFragmentManager().beginTransaction().add(R.id.fragment_container, fragmentToBeAdded, tag).commit();

기존 조각을 식별하려면

getFragmentManager().findFragmentByTag(fragmentName);

Tom의 답변 외에도 replace 메소드는 add 메소드 외에도 fragment 태그를 지원합니다.


When using a tag please do make sure to add the

fragmentTransaction.addToBackStack(null); 

method so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.

If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.

You can find this at the end of this page.

I lost about 30 minutes trying to figure out why my Fragment was not being found through a simple findFragmentByTag(); call

참고URL : https://stackoverflow.com/questions/9363072/android-set-fragment-id

반응형