Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

android - FragmentManager from Context

I created a new View class. Within that class I need to get access to the FragmentManager, but I cannot figure out how.

Can I access the FragmentManager from a context?

CustomView extends LinearLayout
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Only if the given Context extends Activity (Post-Honeycomb) or FragmentActivity (pre-honeycomb).

In which case you'd have to make 100% sure it's an activity using reflection or try-catch.

try{
  final Activity activity = (Activity) context;

  // Return the fragment manager
  return activity.getFragmentManager();

  // If using the Support lib.
  // return activity.getSupportFragmentManager(); 

} catch (ClassCastException e) {
  Log.d(TAG, "Can't get the fragment manager with this");
}

Thought I recommend refactoring so a View is really just meant for showing stuff and shouldn't actually modify the state of your app, but that's my opinion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...