如何在活动中绑定片段(来自xml)?

时间:2017-11-01 15:02:04

标签: butterknife

在我的xml中我有片段:

 <fragment
        android:id="@+id/brandDetailsFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/brandBottomContainer"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/brandDetailsToolBar" />

在我的活动中:

public class BrandDetailsActivity extends AppCompatActivity {
    @BindView((R.id.brandDetailsFragment))
    BrandDetailsFragment brandDetailsFragment;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.brand_details_activity);
            ButterKnife.bind(this);
        }

但是我得到错误(在运行时):

e: BrandDetailsActivity.java:29: error: @BindView fields must extend from View or be an interface. (com.myproject.android.customer.ui.BrandDetailsActivity.brandDetailsFragment)
e: 

e:     BrandDetailsFragment brandDetailsFragment;
e:                          ^
e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)

我知道片段不会扩展查看。但我需要活动中的绑定片段。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您应该将片段添加到此类活动中,因为活动会添加片段getSupportFragmentManager

    FragmentTransaction ft = mFm.beginTransaction();
    ft.add(fragment);
    ft.commit();