현재 조각 개체를 가져옵니다
내에서 main.xml
내가 가진
<FrameLayout
android:id="@+id/frameTitle"
android:padding="5dp"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="@drawable/title_bg">
<fragment
android:name="com.fragment.TitleFragment"
android:id="@+id/fragmentTag"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
그리고 저는 이와 같이 조각 객체를 설정하고 있습니다
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment newFragment = new FragmentType1();
fragmentTransaction.replace(R.id.frameTitle, casinodetailFragment, "fragmentTag");
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
FragmentType2,FragmentType3,...
다른 시간에 다른 유형의 Fragment 객체 ( )를 설정하고 있습니다. 이제 어느 시점에서 현재 어떤 개체가 있는지 식별해야합니다.
에서 짧은 나는 같은 것을 할 필요가 :
Fragment currentFragment = //what is the way to get current fragment object in FrameLayout R.id.frameTitle
나는 다음을 시도했다
TitleFragment titleFragmentById = (TitleFragment) fragmentManager.findFragmentById(R.id.frameTitle);
과
TitleFragment titleFragmentByTag = (TitleFragment) fragmentManager.findFragmentByTag("fragmentTag");
그러나 객체 (titleFragmentById 및 titleFragmentByTag)는 둘 다null
무엇입니까?
에 대해 사용 Compatibility Package, r3
하고 개발 중입니다 API level 7
.
findFragmentById()
그리고 findFragmentByTag()
우리가 사용하는 조각을 설정 한 경우 작동 fragmentTransaction.replace
또는 fragmentTransaction.add
것이지만 return null
우리가 XML에서 (I 내에서 한 일을 같은 객체를 설정 한 경우 main.xml
). XML 파일에 뭔가 빠진 것 같습니다.
이제 어느 시점에서 현재 어떤 객체가 있는지 식별해야합니다
전화 findFragmentById()
에 FragmentManager
당신에있는 조각을 결정 R.id.frameTitle
컨테이너입니다.
이 시도,
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
이것은 당신에게 현재 조각을 줄 것이고, 당신은 그것을 조각 클래스와 비교하고 당신의 일을 할 수 있습니다.
if (currentFragment instanceof NameOfYourFragmentClass) {
Log.v(TAG, "find the current fragment");
}
onAttachFragment 이벤트를 사용 하여 활성화 된 조각을 포착하는 데 유용 할 수 있다고 생각합니다 .
@Override
public void onAttachFragment(Fragment fragment) {
// TODO Auto-generated method stub
super.onAttachFragment(fragment);
Toast.makeText(getApplicationContext(), String.valueOf(fragment.getId()), Toast.LENGTH_SHORT).show();
}
나는 당신이해야한다고 생각합니다 :
Fragment currentFragment = fragmentManager.findFragmentByTag("fragmentTag");
그 이유는 "fragmentTag"태그를 추가 한 마지막 조각 (바꾸기라고했을 때)으로 설정했기 때문입니다.
이것은 가장 간단한 해결책이며 나를 위해 일합니다.
1.) 조각을 추가합니다
ft.replace(R.id.container_layout, fragment_name, "fragment_tag").commit();
2.)
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment currentFragment = fragmentManager.findFragmentById(R.id.container_layout);
if(currentFragment.getTag().equals("fragment_tag"))
{
//Do something
}
else
{
//Do something
}
조각 목록을 가져 와서 마지막 조각을 볼 수 있습니다.
FragmentManager fm = getSupportFragmentManager();
List<Fragment> fragments = fm.getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
But sometimes (when you navigate back) list size remains same but some of the last elements are null. So in the list I iterated to the last not null fragment and used it.
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null) {
for(int i = fragments.size() - 1; i >= 0; i--){
Fragment fragment = fragments.get(i);
if(fragment != null) {
// found the current fragment
// if you want to check for specific fragment class
if(fragment instanceof YourFragmentClass) {
// do something
}
break;
}
}
}
}
It might be late but I hope it helps someone else, also @CommonsWare has posted the correct answer.
FragmentManager fm = getSupportFragmentManager();
Fragment fragment_byID = fm.findFragmentById(R.id.fragment_id);
//OR
Fragment fragment_byTag = fm.findFragmentByTag("fragment_tag");
Maybe the simplest way is:
public MyFragment getVisibleFragment(){
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
for(Fragment fragment : fragments){
if(fragment != null && fragment.getUserVisibleHint())
return (MyFragment)fragment;
}
return null;
}
It worked for me
You can create field in your parent Activity Class:
public class MainActivity extends AppCompatActivity {
public Fragment fr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
And then inside each fragment class:
public class SomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
((MainActivity) getActivity()).fr = this;
}
Your 'fr' field is current fragment Object
It's working also with popBackStack()
I know it's been a while, but I'll this here in case it helps someone out.
The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following
MyFragmentClass fragmentList =
(MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);
kept on returning null. My mistake was really silly, in my xml file:
<fragment
android:tag="@+id/fragementID"
android:name="com.sf.lidgit_android.content.MyFragmentClass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
The mistake was that I had android:tag INSTEAD OF android:id.
@Hammer response worked for me, im using to control a floating action button
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
android.app.Fragment currentFragment = getFragmentManager().findFragmentById(R.id.content_frame);
Log.d("VIE",String.valueOf(currentFragment));
if (currentFragment instanceof PerfilFragment) {
PerfilEdit(view, fab);
}
}
});
If you are defining the fragment in the activity's XML layour then in the Activity
make sure you call setContentView()
before calling findFragmentById()
.
If you are using the BackStack...and ONLY if you are using the back stack, then try this:
rivate Fragment returnToPreviousFragment() {
FragmentManager fm = getSupportFragmentManager();
Fragment topFrag = null;
int idx = fm.getBackStackEntryCount();
if (idx > 1) {
BackStackEntry entry = fm.getBackStackEntryAt(idx - 2);
topFrag = fm.findFragmentByTag(entry.getName());
}
fm.popBackStack();
return topFrag;
}
If you are extending from AbstractActivity, you could use the getFragments() method:
for (Fragment f : getFragments()) {
if (f instanceof YourClass) {
// do stuff here
}
}
참고URL : https://stackoverflow.com/questions/6750069/get-the-current-fragment-object
'Programing' 카테고리의 다른 글
PHPMailer 문자 인코딩 문제 (0) | 2020.05.26 |
---|---|
urllib 및 python을 통해 사진 다운로드 (0) | 2020.05.26 |
최대 또는 기본? (0) | 2020.05.26 |
Openssl은 내부 또는 외부 명령으로 인식되지 않습니다 (0) | 2020.05.26 |
로드시 CSS3 전환 애니메이션? (0) | 2020.05.26 |