我想让我的按钮调用片段中的方法

I want my button to call a method in a fragment

所以我有 (WorkoutList Activity) -> (WorkoutList Fragment) -> (ExerciseList Fragment) -> (addExercise Fragment)

AddExercise 中有一个按钮,我希望它调用 ExerciseList 中的一个方法

问题是,在当前设置下,我得到`Attempt to invoke virtual method

void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

XML 添加练习按钮:

<Button
    android:id="@+id/add_exercise_button"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/add_workout_message_done"
    android:layout_weight="0"
    android:onClick="addExerciseDone"
    />

OnCreateView 方法中的 ExerciseList 代码片段:

     View rootView = inflater.inflate(R.layout.fragment_exercise_list, container, false);
    Button AddExerciseDoneButton = (Button) getActivity().findViewById(R.id.add_exercise_button);
    AddExerciseDoneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addExerciseDone(v);
        }
    });

注意: 这是对 chinmay 的建议的回应** 我将 viewroot 设置为 ExerciseList 的 XML 文件,这样我就可以让我的适配器显示我的列表视图,所以我不确定如何 return 我创建的视图以便我可以引用按钮。例如,我做了

final View tmpView = inflater.inflate(R.layout.fragment_add_exercise, container, false);

    Button AddExerciseDoneButton = (Button) tmpView.findViewById(R.id.add_exercise_button);

您收到 NullPointerException,因为您对 AddExerciseDoneButton 的引用无效。 您尚未指定任何具有按钮 ID - R.id.add_exercise_button 的布局,当您尝试使用该按钮时,它将提供 NullPointer

相反,您的 onCreateView 应该看起来像

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

让您的视图引用 onCreateView 返回的视图,它将获得按钮 ID

供参考:http://developer.android.com/guide/components/fragments.html

你正在做这个

View rootView = inflater.inflate(R.layout.fragment_exercise_list, container, false);
    Button AddExerciseDoneButton = (Button) getActivity().findViewById(R.id.add_exercise_button);

而不是这个

     View rootView = inflater.inflate(R.layout.fragment_exercise_list, container, false);
        Button AddExerciseDoneButton = (Button) 
rootView.findViewById(R.id.add_exercise_button);