我试图访问在片段的ConstraintLayout中创建的按钮,但它最终返回null。它实际上能够找到ConstraintLayout和其中的卡片视图,但不能找到卡片的按钮或文本视图。
附加片段文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.gallery.QuestionFragment"
android:id="@+id/contraint_layout">
<androidx.cardview.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="3dp"
android:layout_marginStart="3dp"
android:layout_marginEnd="3dp"
app:cardCornerRadius="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"
android:layout_margin="5sp"
android:text="@string/questions_intro"/>
</androidx.cardview.widget.CardView>
<com.google.android.material.button.MaterialButton
android:id="@+id/add_question_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_marginTop="28dp"
android:text="@string/add_question"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/card_view"
android:visibility="visible"
app:layout_constraintVertical_bias="0.037"
tools:layout_editor_absoluteX="3dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
我编写的访问它的代码
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_questions, container, false);
Button addQuestionButton = view.findViewById(R.id.add_question_button);
addQuestionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "HI", Toast.LENGTH_LONG).show();
}
});
return view;
}
为简洁起见,删除了布局边距。
任何帮助都将不胜感激。
1条答案
按热度按时间sqougxex1#
在Java代码中,将Button更改为MaterialButton