java - 如何修复:错误:不是封闭类:上下文
问题描述
我在标题中指出了错误: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 但我希望你能理解我......
解决方案
您可以使用 getContext() 在片段中启动活动
Intent intent = new Intent(getContext(), AnmeldungButton.class);
startActivity(intent);
推荐阅读
- html - 有没有一种简单的方法来提取html元素中的部分css?
- c++ - 将值插入标准 C++ 数组的正确索引(升序)
- knockout.js - 淘汰赛 - 两个可观察的字段相互更新
- javascript - 我该如何处理错误,忽略它并继续使用该功能?不和谐.js
- sql - SQL - 在两列中对字符进行分组和计数
- c - 使用两个管道在父进程和子进程之间进行通信
- ios - SwiftUI 背景默认为渐变
- c# - .csproj 中指定的 NuGet 包的版本号与包的版本号不匹配
- java - 从黄瓜 4.2.3 升级到 5.1.3 后 Cucumber runner 类初始化错误
- r - 有没有办法使用闪亮的下载按钮从应用程序下载(非导入/操作)数据?