1

i'm having a fragment that i want to use it as a library in other projects. i created a library module and copy-paste all my fragment code and resources to library mode and then to use that library module i'm writing the following code in activity's xml

<androidx.fragment.app.FragmentContainerView
android:id="@+id/fragmentContainerView"
android:name="com.dhirunand.meter.MeterFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

and in java file

MeterFragment meterFragment = new MeterFragment();
String selectedNumber = meterFragment.getSelectedNumber();

visually library mudule is working fine but i'm not able to fetch data from the library module

project github url https://github.com/dhirunand/meter--number-picker

dhirunand
  • 41
  • 1
  • 6

1 Answers1

2

when you are using new MeterFragment() line then you are creating NEW fragment, not using one attached to FragmentContainerView. this NEW one isn't visible on screen, its just created in memory, not shown (as you haven't posted attaching code), so getSelectedNumber() will return default value instead this set in MeterFragment attached to FragmentContainerView

you should obtain this "real" existing and visible instance from XML by

FragmentContainerView fcv = (FragmentContainerView) findViewById(R.id.fragmentContainerView);
MeterFragment meterFragment = (MeterFragment) fcv.getFragment();
snachmsm
  • 17,866
  • 3
  • 32
  • 74
  • yes i understood my problem thank you., but Android Studio cannot resolve getFragment() method from FragmentContainerView. i checked this post https://stackoverflow.com/questions/68018322/cant-find-method-getfragment-in-my-fragmentcontainerview-object but didn't got any soluion – dhirunand Jan 05 '22 at 05:55
  • looks like this `getFragment()` was introduced later, have you updated your lib `import`? – snachmsm Jan 05 '22 at 08:45
  • after updating the import implementation "androidx.fragment:fragment:1.4.0" it's working fine. thank you so much – dhirunand Jan 05 '22 at 12:02