我想实现一个WifiScanner侦听器到我的ScanFragment,但我收到这个错误:java.lang.ClassCastException: emilsoft.wifitest3.MainActivity cannot be cast to emilsoft.wifitest3.WifiScanner$Listener
我已经做了这与正常的活动,现在我试图将其转换为碎片,我目前正在了解它们。 我做了很多研究,但找不到工作解决方案。我有评论哪里有错误ClassCastException:MainActivity不能转换为侦听器
所以我主要活动代码:
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。可能是一个非常愚蠢的解决方案,但我找不到它。
在此先感谢!
这工作谢谢! – Automatik
@Pelocho工作的人!!谢谢 –