使用ButterKnife在布局中使用多个<include />标记

Ste*_*han 8 android butterknife

我有一个布局,其中我多次包含相同的子布局,每个子布局具有不同的角色:

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <include
        android:id="@+id/settings_eco_seekarc"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/settings_arc" />

    <include
        android:id="@+id/settings_comfort_seekarc"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/settings_arc" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

如果我以这种方式找到视图,它会起作用:

View eco = root.findViewById(R.id.settings_eco_seekarc);
mEcoSeekArc = (SeekArc) eco.findViewById(R.id.settings_seekarc);
mEcoLeaf = (ImageView) eco.findViewById(R.id.settings_leaf_img);
mEcoText = (TextView) eco.findViewById(R.id.settings_text);
View cmf = root.findViewById(R.id.settings_comfort_seekarc);
mComfortSeekArc = (SeekArc) cmf.findViewById(R.id.settings_seekarc);
mComfortLeaf = (ImageView) cmf.findViewById(R.id.settings_leaf_img);
mComfortText = (TextView) cmf.findViewById(R.id.settings_text);
Run Code Online (Sandbox Code Playgroud)

我现在在我的项目中介绍ButterKnife,我希望我可以简单地注释每个视图(以下显然不起作用,我可以看到原因)并稍后使用每个包含的布局根注入它们:

@InjectView(R.id.settings_seekarc)
SeekArc mEcoSeekArc;
@InjectView(R.id.settings_leaf_img)
ImageView mEcoLeaf;
@InjectView(R.id.settings_text)
TextView mEcoText;
@InjectView(R.id.settings_seekarc)
SeekArc mComfortSeekArc;
@InjectView(R.id.settings_leaf_img)
ImageView mComfortLeaf;
@InjectView(R.id.settings_text)
TextView mComfortText;

//then later...
View eco = root.findViewById(R.id.settings_eco_seekarc);
ButterKnife.inject(this, eco);
View cmf = root.findViewById(R.id.settings_comfort_seekarc);
ButterKnife.inject(this, cmf);
Run Code Online (Sandbox Code Playgroud)

但是,这样做会导致我在第二次注射时出现这个错误:

错误:(81,13)错误:尝试在'mEcoSeekArc'上使用已注入的ID 2131493185的@InjectView.

我的问题是:在这种情况下有没有办法使用ButterKnife?

Bud*_*ius 9

你可以像这样使用某种类型的子容器:

public static class SettingsArcLayout {
  @InjectView(R.id.settings_text) public TextView mEcoText;
  @InjectView(R.id.settings_leaf_img) public ImageView mComfortLeaf;
  // etc...
}
Run Code Online (Sandbox Code Playgroud)

那你就拥有它

SettingsArcLayout layout1 = new SettingsArcLayout();
SettingsArcLayout layout2 = new SettingsArcLayout();
Run Code Online (Sandbox Code Playgroud)

然后:

ButterKnife.inject(this); // inject eco and cmf
ButterKnife.inject(layout1, eco);
ButterKnife.inject(layout2, cmf);
Run Code Online (Sandbox Code Playgroud)

通过这个课程你可以使用:

layout1.mEcoText.setText(... etc
Run Code Online (Sandbox Code Playgroud)