2 xiaoyan 12 xiaoyan_12 于 2013.04.16 16:56 提问

在 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();
如何解决这个问题呢?

3个回答

dongzibin
dongzibin   2013.04.17 09:33
已采纳

直接让TopRecipesFragment实现OnConnectingToInternet这个接口

luhuajcdd
luhuajcdd   2013.04.16 23:41

Fragment 里面有个getActivity()方法,可以试试

kevinpeng1990
kevinpeng1990   2015.02.02 15:21

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);
}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!