Search code examples
androidviewbutterknife

Butterknife how to bindView from a different Views


in my project I have this case:

@BindView(R.id.viewpager)
ViewPager viewPager;
TabLayout tabLayout;
AddParkingFragmentListener listener;



public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View inflatedView = inflater.inflate(R.layout.fragment_add_parking, container, false);

    ButterKnife.bind(this, inflatedView);

    tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
    tabLayout.setVisibility(View.VISIBLE);

    return inflatedView;
}

where I need to bind a view that is in the activity_main.xml layout. I've thought that I could use an interface to disable the visibility directly in the MainActivity, but I would also know if there is the possibility to bind this view using Butterknife, because in the MainActivity I have also this problem:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View view = navigationView.getHeaderView(0);
    profile = (ImageView) view.findViewById(R.id.imgPro); 

    //this views are in the navigation view, how to bind using butterknife?
    logo = (ImageView) view.findViewById(R.id.logo);

    email = (TextView) findViewById(R.id.email_profile);

    ButterKnife.bind(this);

}

is there a way to do this or I need to use findViewById() method?

Thanks


Solution

  • According the oficial documentation from Butter Knife Library

    They have included findById methods which simplify code that still has to find views on a View, Activity, or Dialog. It uses generics to infer the return type and automatically performs the cast.

    View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
    TextView firstName = ButterKnife.findById(view, R.id.first_name);
    TextView lastName = ButterKnife.findById(view, R.id.last_name);
    ImageView photo = ButterKnife.findById(view, R.id.photo);
    

    Add a static import for ButterKnife.findById and enjoy even more fun.

    Source: http://jakewharton.github.io/butterknife/