我在m项目中添加了雅虎天气库。然后我尝试将YahooWeatherInfoListener实现到主片段中。
有个问题。
在AsyncTask
内部,我无法将YahooWeatherInfoListener
投射到片段中。
我觉得AsncTask里面有我做错的事。请看一下:
import zh.wang.android.apis.yweathergetter4a.WeatherInfo;
import zh.wang.android.apis.yweathergetter4a.YahooWeather;
import zh.wang.android.apis.yweathergetter4a.YahooWeather.SEARCH_MODE;
import zh.wang.android.apis.yweathergetter4a.YahooWeatherInfoListener;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeFragment extends Fragment implements YahooWeatherInfoListener {
public HomeFragment(){}
private TextView Temperature;
private YahooWeather mYahooWeather = YahooWeather.getInstance(5000, 5000, true);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Temperature = (TextView) rootView.findViewById(R.id.txtLabel);
new searchByGPS().execute();
return rootView;
}
private class searchByGPS extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);
return null;
}
protected void onPostExecute(Void unused) {
}
}
@Override
public void gotWeatherInfo(WeatherInfo weatherInfo) {
// TODO Auto-generated method stub
Temperature.setText(weatherInfo.getCurrentTempC());
}
}
这是因为在中
(YahooWeatherInfoListener) this
CCD_ 3是指CCD_。相反,您需要使用:
(YahooWeatherInfoListener) HomeFragment.this
实现这一点的更清洁的方法是:
private class SearchByGPSTask extends AsyncTask<Void, Void, Void>{
private YahooWeatherInfoListener mListener;
public SearchByGPSTask( YahooWeatherInfoListener listener ) {
super();
mListener = listener;
}
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), mListener );
return null;
}
protected void onPostExecute(Void unused) {
}
}
(注意:类通常是大写的,更好的名词——"searchByGPS"听起来像是一个方法,而"SearchByGPSTask"表示它是一个用来做某事的类。(
protected Void doInBackground(Void... unused) {
mYahooWeather.setNeedDownloadIcons(true);
mYahooWeather.setSearchMode(SEARCH_MODE.GPS);
mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) HomeFragment.this);
return null;
}
您必须将this
更改为HomeFragment.this
,因为它直接连接到您的AsyncTask。
使用此行mYahooWeather.queryYahooWeatherByGPS(getActivity().getApplicationContext(), (YahooWeatherInfoListener) this);
,您正试图将AsyncTask
强制转换为YahooWeatherInfoListener
。使用HomeFragment.this
代替