问题描述
- 在 fragment 如何实例化接口?
-
android 程序中,在一个 fragment activity 中有一个 progressbar。当任何 fragment 调用接口时,这个 progress bar 就会设置为可见的。public class MainScreen extends FragmentActivity { public interface OnConnectingToInternet { public void showProgressbar(boolean flag); } // rest of codes . . . // Implementing Interface public void showProgressbar(boolean flag) { if(flag){ myProgressbar.showProgressBar(); } else { myProgressbar.hideProgressBar(); } } }
每一个fragment应该连接网络获取数据,但是在这之前要调用接口。其中一个fragment的代码如下:
public class TopRecipesFragment extends Fragment { private OnConnectingToInternet onConnectingToInternet; @Override public void onAttach(Activity activity) { super.onAttach(activity); // onConnectingToInternet = (OnConnectingToInternet) activity; Log.i(TAG, "Fragment attached to activity."); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); New MyAsyncTask.execute(); } public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { Log.i(TAG, "myAsyncTask is about to start..."); onConnectingToInternet.showProgressbar(true); } @Override protected Boolean doInBackground(Void... params) { ... } @Override protected void onPostExecute(Boolean result) { Log.i(TAG, "myAsyncTask is about to start..."); onConnectingToInternet.showProgressbar(false); } }
问题是我不知道如何实例化这个接口。如果我不加入这行:
onConnectingToInternet = (OnConnectingToInternet) activity;
然后运行程序时,就会出错NullPointerException
。但是,如果我这样实例化,然后程序就崩溃。我用通常的做法也不行:
onConnectingToInternet = new MainScreen();
如何解决这个问题呢?
解决方案
直接让TopRecipesFragment实现OnConnectingToInternet这个接口
解决方案二:
Fragment 里面有个getActivity()方法,可以试试
解决方案三:
public class MainScreen extends FragmentActivity {
private OnConnectingToInternet onConnectingToInternet ;
@Override
public void onAttach(Activity activity) {
try {
mCallback = (onConnectingToInternet) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnResolveTelsCompletedListener");
}
super.onAttach(activity);
}
public interface OnConnectingToInternet {
public void showProgressbar(boolean flag);
}