首页 > 解决方案 > 如何修复:错误:不是封闭类:上下文

问题描述

我在标题中指出了错误:error: not an enclosing class: Context

我已经在其他一些论坛上尝试过解决这个问题,但他们无能为力,我检查了 youtube 和 stackoverflow 上的其他问题,但找不到这个问题的答案。

我的代码如下所示:

public class TermineFragment extends Fragment {

    private Button button;
    Context c;

    @Override
    public void onAttach(Context c) {
        super.onAttach(c);
        Context context = c;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_3, container, false);
        button = view.findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(Context.this, AnmeldungButton.class));
                startActivity(intent);
            }
        });

        return view;
    }
}

这会产生错误:

error: not an enclosing class: Context

来自以下行: Intent intent = new Intent(getActivity(Context.this,AnmeldungButton.class));

我希望我在 Fragment AnmeldungButton.java 中的按钮是我的意思是在 Activity 但我希望你能理解我......

标签: javaandroidandroid-context

解决方案


您可以使用 getContext() 在片段中启动活动

Intent intent = new Intent(getContext(), AnmeldungButton.class);                   
startActivity(intent);

推荐阅读