android - how change fragment textview with own java class? -
i tried change textview in activity of fragment in 3 cases, can't change textview.
there solution change textview of fragment in own fragment_activity or main_activity?
fragment.java
@override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); if (getarguments() != null) { mparam1 = getarguments().getstring(arg_param1); mparam2 = getarguments().getstring(arg_param2); } textview textview = (textview) getview().findviewbyid(r.id.textview1); textview.settext("done!"); } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.fragment_blank_fragment2, container, false); textview tv = (textview) view.findviewbyid(r.id.textview1); tv.settext("done!"); return view; } @override public void onactivitycreated (bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); textview tv = (textview) getview().findviewbyid(r.id.textview1); tv.settext("done!"); }
fragment.xml
... <textview android:textcolor="@color/myblack" android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="test" android:textappearance="?android:attr/textappearancemedium" /> ....
calling fragment class view in mainactivity:
@override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main_weixin); getwindow().setsoftinputmode(windowmanager.layoutparams.soft_input_state_always_hidden); instance = this; ... view view2 = mli.inflate(r.layout.fragment_blank_fragment2, null); views.add(view2); ... }
thing know
- in oncreate of fragment
getview()
returns null because still view in not created. - create method in fragment set value
textview
activity using fragment instance.
example : fragment
public class fragment1 extends fragment { textview tv; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view = inflater.inflate(r.layout.fragment_blank_fragment2, container, false); tv = (textview) view.findviewbyid(r.id.textview1); tv.settext("done!"); return view; } public void setviewtext(string text){ tv.settext(text); } }
activity
public class myactivity extends fragmentactivity { fragment1 fragment1; @override protected void oncreate(bundle arg0) { super.oncreate(arg0); setcontentview(r.layout.activity_fragment); //as using static fragment create fragment instance using findfragmentbyid(id) fragment1 = (fragment1) getsupportfragmentmanager().findfragmentbyid(r.id.fragment1); fragment1.setviewtext("message"); } }
visit official doc communicating other fragments
happy_coding :)
Comments
Post a Comment