How do I find the ID of a fragment? Alternatively, how do I give the fragment an ID?

StackOverflow https://stackoverflow.com/questions/20283344

  •  06-08-2022
  •  | 
  •  

Вопрос

(First, I'm aware this question has been asked plenty of times, but I haven't found an applicable answer)

I have a fragment created as such:

inflater.inflate ( R.layout.fragment_task_ongoing, container, false );

What I'd like, is to use findFragmentById in the FragmentActivity, like this:

TaskActiveFragment f = ( TaskActiveFragment ) getSupportFragmentManager ().findFragmentById ( R.id.fragment_task_ongoing );

Unfortunately, this returns null. The apparent reason is that the id used as a parameter, is the id of the RelativeLayout being inflated, and not the Fragment. First lines of the layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_task_ongoing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >

So, how do I find out what ID the fragment has? If it doesn't have an ID, how do I give it one? Programatically? XML?

Edit: My fragments are added to a FragmentStatePagerAdapter, which is then added to a ViewPager.

Это было полезно?

Решение

Provided you keep a reference to your FragmentStatePagerAdapter and to the index of the Fragment in view, you can call getItem(int position) on your FragmentStatePagerAdapter, which will return the Fragment.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top