android - Programming principle for accessing view from fragment to activity's views -


i have activity , fragment inside it. main activity layout:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"           android:layout_width="match_parent"           android:layout_height="match_parent"> <button     android:id="@+id/btn_login"     android:text="login"     android:layout_width="wrap_content"     android:layout_height="wrap_content"/>  <framelayout     android:id="@+id/fl_content"     android:layout_width="match_parent"     android:layout_height="match_parent" />  </linearlayout> 

after replace fragment fl_content by:

fragmentmanager fm = getfragmentmanager(); fragmenttransaction fragmenttransaction = fm.begintransaction(); fragmenttransaction.replace(r.id.fl_conent, new myfragment()); fragmenttransaction.commit(); 

from myfragment, want cho change text/color of btn_login, knowledge can: first way, inside myfragment:

button btnlogin = (button) getactivity().findviewbyid(r.id.btn_login); btnlogin.settext("another text"); 

this way think fragment should not access activity's login button (and other acitivty's view if have if can) because violate encapsulation or loose-coopling in programming.

the second way: create listener/callback

public interface changelistener {     void onchanged(); } 

then set fragment, activity implement listener

myfragment myfragment = new myfragment(); myfragment.setonchangelistener(new changelistener() {      @override      public void onchanged() {          btnlogin.settext("another text");      } } fragmenttransaction.replace(r.id.fl_conent, myfragment); fragmenttransaction.commit(); 

whenever need change btnlogin text, myfragment call mchangelistener.onchanged(); activity change it's btnlogin itshelf. way keep encapsulation - loose-coopling.

i think should use second way, or may way not listed here, how you? glad hear opinion. thanks!

@jim coven: "startactivityforresults activity, use setresults in fragment". give me code snippet understand :d

i'd prefer 2nd way. however, still require external call set listener. alternatively, if fragment's purpose update results in activity, try:

startactivityforresults activity, use setresults in fragment.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -