我正在尝试为我的 ScanFragment 实现一个 WifiScanner 监听器,但我收到此错误:java.lang.ClassCastException: emilsoft.wifitest3.MainActivity cannot be cast to emilsoft.wifitest3.WifiScanner$Listener
我已经用普通的 Activity 做到了这一点,现在我正在尝试将其转换为 fragment ,我目前正在了解它们。
我做了很多研究,但找不到可行的解决方案。我已经评论了有错误的代码
所以我的 主要 Activity :
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
我的 SectionsPagerAdapter 类 :
public class SectionsPagerAdapter extends FragmentPagerAdapter{
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: return ScanFragment.newInstance();
}
return null;
}
我的 ScanFragment :
public class ScanFragment extends Fragment implements WifiScanner.Listener {
private ScanCollector sc;
private WifiManager wifi;
public ScanFragment() {}
public static ScanFragment newInstance() {
return new ScanFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_scan_results, container, false);
wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
sc = new ScanCollector(this.getContext()); //THE ERROR STARTS HERE
return result;
}
我的 ScanCollector 类 (处理添加到 WifiScanner 类的监听器):
public class ScanCollector {
// The context wrapper that we'll use for accessing system services, receiving
// broadcasts from the WifiManager
private final Context context;
private WifiScanner.Listener listener;
public ScanCollector(Context context) {
if (context == null)
throw new NullPointerException();
this.context = context;
this.listener = (WifiScanner.Listener)context; //THE ERROR IS HERE
}
问题是我无法将正确的上下文传递给我的 ScanCollector 类,然后该类会将其转换为 WifiScanner.Listener。可能是一个非常愚蠢的解决方案,但我找不到它。
提前致谢!
最佳答案
一件事是 context
,另一件事是 WifiScanner.Listener
。您的 ScanCollector
需要两者,因此请同时传递它们:
public ScanCollector(Context context, WifiScanner.Listener listener) {
if (context == null)
throw new NullPointerException();
this.context = context;
this.listener = listener
}
当你创建它时:
sc = new ScanCollector(getActivity(), this);