xiaoyan_12
2013-04-16 08:56
采纳率: 84.9%
浏览 5.7k

在 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条回答 默认 最新

  • dzb 2013-04-17 01:33
    已采纳

    直接让TopRecipesFragment实现OnConnectingToInternet这个接口

    已采纳该答案
    打赏 评论
  • luhuajcdd 2013-04-16 15:41

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

    打赏 评论
  • simon_xiaopeng 2015-02-02 07: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);
    }

    打赏 评论

相关推荐 更多相似问题