如何解决:错误:不是封闭的类:上下文

时间:2019-06-29 20:57:08

标签: java android android-context

我在标题中发现了错误: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中的按钮是我在活动中的意思,但我希望您理解我...

3 个答案:

答案 0 :(得分:0)

您可以将getContext()用于片段中的开始活动

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

答案 1 :(得分:0)

使用此代码

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

这是您正在使用的以错误方式传递参数的问题。

Intent(Context packageContext, Class<?> cls)

答案 2 :(得分:0)

public class TermineFragment extends Fragment {

Context c;
@Override
    public void onAttach(Context c) {
        super.onAttach(c);
        this.c = c; //this is one of the best way to get context of the activity to which the particular activity is associated with
    }
   @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(c,AnmeldungButton.class);//Pass the context like this.
           startActivity(intent);
        });
        return view;
    }
}