Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the FragmentManager by the views ID?

How can I get the FragmentManager of a View?

Assuming I have a layout like this:

<?xml version="1.0" encoding="utf-8"?>
...
<fragment android:name="com.example.MyFragment"
        android:id="@+id/thefragmentsid" >
</fragment>
...

Here is my pseudo code (I know that not even FragmentView exists, but I guess you know what I mean)

FragmentView fw = (FragmentView) activity.findViewById( R.id.thefragmentsid );
FragmentManager goal = fw.getFragment().getFragmentManager();

And here is an example use case:

public class MyFragment extends Fragment{
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate( R.layout.my_fragments_view, container, false );
    }
}

public class MainActivity extends FragmentActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        findViewById( R.id.thefragmentsid ).setOnTouchListener( new OnTouchListener(){
            @Override
            public boolean onTouch( View v, MotionEvent event ){
                FragmentView fw = (FragmentView) findViewById( R.id.thefragmentsid );
                FragmentManager fm = fw.getFragment().getFragmentManager();
                // Do something with the fragment manager
                return false;
            }
        } );
    }
}

EDIT: I do not have access to any Fragment-Object in any way I know. Maybe there is a hidden way but exactly for that I'm asking!

NEXT EDIT: (Just to complete the question afterwards) I'm using the Google Support Package!

PS: I don't want to give too much involved infos because it's a general question which requires a general answer and could appear occasionally.

like image 961
Matmarbon Avatar asked Dec 01 '25 17:12

Matmarbon


1 Answers

Okay, it is really my own mistake, I see. I thought it had to be a function called getFragmentManager() but exactly that was the mistake.

The correct function is called getSupportFragmentManager() since I use Googles Support Package.

But one has to say there is a big trap because inside of a Fragment even with the Support Package one can use the Fragments function getFragmentManager() but inside of an FragmentActivity it's suddenly getSupportFragmentManager().

I admit it's great disgrace, especially that I thought it wouldn't be a necessary information, that I use the Support Package. I thought it would keep the question more general but I see I never should retain any information. For future questions :)

like image 161
Matmarbon Avatar answered Dec 03 '25 07:12

Matmarbon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!