Access Toolbar (and its children) from fragment?

人盡茶涼 提交于 2019-12-03 16:10:54
javmarina

I'm not sure if this works, but you can try it.

    final AppCompatActivity act = (AppCompatActivity) getActivity();
    if (act.getSupportActionBar() != null) {
        Toolbar toolbar = (Toolbar) act.getSupportActionBar().getCustomView();
    }

Toolbar is essentially a ViewGroup.

no need to code a lot: follow this

in Kotlin:

   var toolbar = activity.findViewById<Toolbar>(R.id.toolbar)
    toolbar.setTitle("Rashid")

in Java:

 Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
 toolbar.setTitle("Rashid")

The communication between Activity and Fragments (the same holds for any Java components) should be done through an Interface.

For your case define an interface

public interface IOperateOnToolbar {
    //methods allowing to communicate with toolbar
    public void setToolbarColor(Color c);
    public void setImageView1Resource(int resID);
    public void setImageView2Resource(int resID);
    //.....
}

So you have an Activity

 public class MainActivity extends AppCompatActivity implements IOperateOnToolbar {

   //onCreate, onDestroy ...

   public void setToolbarColor(Color c) {
        //implementation follows
   }
   public void setImageView1Resource(int resID) {
       imageView1.setBackgroundResource(resID);
   }
   public void setImageView2Resource(int resID) {
       imageView2.setBackgroundResource(resID);
   }
}

And your Fragment

public class MyFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {    
         IOperateOnToolbar toolbarCallback = (IOperateOnToolbar) getActivity();
    }
}

Using the interfaces for communication between components has the following benefits:

  • If you replace the "MainActivity" with another one ("ActivityX" which also implements IOperateOnToolbar), you don't have to edit anything in "MyFragment"

  • "MyFragment" has access only to those methods, which are exposed by IOperateOnToolbar interface.

Please chceck this docu, where google advises the communication (between fragments, but should be the in principle the same) using interfaces.

this will do the job for you

((MainAcivity)this.getActivity()).getToolbar();

Here you can access toolbar children:

TextView toolbarTextView  = (TextView) ((MainActivity) this.getActivity()).findViewById(R.id.toolbarTitle);
toolbarTextView.setText("Hello");

In my case I has an activity and a navigation drawer that replaces this activity fragment with other fragments. If you implement toolbar views (spinners, Buttons..) in the main activity, the fragments that will be replaced in this activity can see toolbar and interact with its views.

else if, you need to handle actions depending on this views, you can use: getActivity.findViewById(); inside fragment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!