1

I am starting to use ButterKnife and I got it is working inside fragment with views that are inflated.

But I have a question, is it possible to get views which aren't inflated?

For example, I have a toolbar inside of my MainActivity, but not inside the fragment. Can I access to this toolbar using ButterKnife?.

And other question. I tried to get the toolbar height using:

Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
int toolbarHeight = toolbar.getHeight();

But this return always 0. How can I get the toolbar size from the view directly? Now I am using:

 getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValueToolbarHeight, true);

But really I would like to get the toolbar from the view.

JavierSegoviaCordoba
  • 6,531
  • 9
  • 37
  • 51
  • If you call inside oncreate to fetch height it will return zero. Call it once the layout is loaded – Fahim Feb 15 '15 at 05:41
  • 1
    If you want to manage a view of the activity, it is the activity the one that should manage it and pass the result to the fragment that is interested. I answer already a question about this topic : http://stackoverflow.com/questions/17436298/how-to-pass-a-variable-from-activity-to-fragment-and-pass-it-back/17436739#17436739 . So via interface you tell your activity to do something, the activity do it (the only condition of the activity is to implementation the interface), then the activity send the result to the fragment you want (either back to the same one or another in the activity). – jpardogo Feb 15 '15 at 14:20

1 Answers1

1

Initialize the view and call this method in on create method

 view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @SuppressLint("NewApi")
     @SuppressWarnings("deprecation") 
    @Override 
    public void onGlobalLayout() {
     //now we can retrieve the width and height 
    int width = view.getWidth(); 
    int height = view.getHeight(); 
    //... //do whatever you want with them //... //this is an important step not to keep receiving callbacks: //we should remove this listener //I use the function to remove it based on the api level!
     if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
     view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
     else
     view.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
    } });
Fahim
  • 12,198
  • 5
  • 39
  • 57