Android 我希望我的按钮调用片段中的方法

Android 我希望我的按钮调用片段中的方法,android,button,fragment,Android,Button,Fragment,所以我有(WorkoutList活动)->(WorkoutList片段)->(ExerciseList片段)->(addExercise片段) AddExercise中有一个按钮,我希望它调用ExerciseList中的一个方法 问题是,在当前的设置中,我尝试调用虚拟方法 void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference 用于A

所以我有(WorkoutList活动)->(WorkoutList片段)->(ExerciseList片段)->(addExercise片段)

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

问题是,在当前的设置中,我尝试调用虚拟方法

void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
用于AddExercise按钮的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"
    />
注: 这是对chinmay建议的回应** 我将viewroot设置为ExerciseList的XML文件,这样我可以使适配器显示我的listview,因此我不确定如何返回我创建的视图,以便引用按钮。比如我

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\u exercise\u按钮的布局,当您尝试使用该按钮时,它将给出空指针

相反,您的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

供参考:

你在这么做吗

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

setContentView
不适用于
Fragment
。而不是使用
onCreateView()
方法。你的问题也不清楚。如果我已经返回了rootView(我正在使用它来设置适配器),该怎么办?按钮位于另一个名为fragment_add_exercise的片段中,我是否必须将此代码放在该类的onCreateView中?如果是这样的话,我遇到了一个问题,我无法从静态上下文引用非静态上下文。很抱歉,AddExerciseDoneButton位于ExerciseList之外的单独文件中。我无法更改rootView的布局,因为我需要更改列表适配器。我现在尝试的是将AddExerciseDoneButton的代码移动到addExercise类。我上次尝试这种方法时遇到的问题是,我无法从静态类引用非静态类。我想引用ExerciseList的原因是为了在列表中添加一些内容。如果该按钮与您尝试使用的当前片段中的布局无关,那么我不会在该片段中使用该按钮
     View rootView = inflater.inflate(R.layout.fragment_exercise_list, container, false);
        Button AddExerciseDoneButton = (Button) 
rootView.findViewById(R.id.add_exercise_button);