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這個接口