android - Butterknife 如何从不同的 View 绑定(bind) View

标签 android view butterknife

在我的项目中我有这种情况:

@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;
}

我需要在 activity_main.xml 布局中绑定(bind)一个 View 。 我想我可以使用一个接口(interface)来直接在 MainActivity 中禁用可见性,但我也想知道是否有可能使用 Butterknife 绑定(bind)此 View ,因为在 MainActivity 中我也有这个问题:

 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);

}

有没有办法做到这一点,或者我需要使用 findViewById() 方法?

谢谢

最佳答案

根据Butter Knife Library的官方文档

它们包含了 findById 方法,这些方法简化了仍然需要在 ViewActivityDialog< 上查找 View 的代码。它使用泛型来推断返回类型并自动执行转换。

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);

ButterKnife.findById 添加静态导入,享受更多乐趣。

来源:http://jakewharton.github.io/butterknife/

关于android - Butterknife 如何从不同的 View 绑定(bind) View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43767240/

相关文章:

android - butterknife 如何注入(inject) actionbar 自定义 View ?

android - EditText 在提供的照片中为该指针使用颜色强调

android - Android 源代码中 Acodec.cpp 的 'A' 是什么意思(在 libstagefright 中)

android - 检测 View 外的触摸

mysql - 我可以创建一个 View ,将每隔几行划分为不同的值吗?

android - Logcat 首先显示 “The specified child already has a parent. You must call removeView() on the child' 的父级。”在我的第二个警报对话框中

java - 获取直到午夜的毫秒数

Android - 使用带有无序列表 html 标签的 Gmail 发送电子邮件

java - 如何在 ListView Android 的页眉和页脚中使用 Butter Knife

java - Proguard while Butterknife 库和其他警告