java - Reusing a fragment class inside an activity -
as not familiar fragments getting quite confused solutions presented on stackoverflow. have tried many different techniques achive task: have class called mapfragment extends fragment. works fine inside viewpager. however, want reuse class different activity. heres sample fragment called mapfragment:
public class mapfragment extends fragment { @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_mapview, container, false); mapview = (mapview) rootview.findviewbyid(r.id.fragment_mapview); mapview.oncreate(savedinstancestate); this.sethasoptionsmenu(true); activity.getactionbar().setdisplayhomeasupenabled(true); initgps(); initviews(); initlisteners(); bundle extras = getarguments(); string url = ""; if(extras.containskey("url")) url = extras.getstring("url"); new loadmarkers().execute(url); return rootview; } }
let´s have activity want used reuse mapfragment above:
public class mapactivity extends generalactivity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // want able display mapfragment inside activity // should here???? enter code here } }
then can anywhere in program call intent on mapactivity knowing display mapfragment within it. possible accomplished?
create layout activity class mapactivity. activity_map.xml
rough snippet
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/frag_container" android:layout_width="match_parent" android:layout_height="match_parent" >
in activity class,
public class mapactivity extends generalactivity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // want able display mapfragment inside activity // should here???? // enter code here setcontentview(r.layout.activity_map); fragment fragment = new mapfragment(); fragmentmanager manager = getsupportfragmentmanager(); manager.begintransaction() .replace(r.id.frag_container, fragment) .commit(); } }
also, in fragment code, expecting bundle. make sure check if bundle not null. since above code, not passing data (setarguments).
hope helps!
Comments
Post a Comment