当前位置: 代码迷 >> java >> 如何在片段上使用接口
  详细解决方案

如何在片段上使用接口

热度:31   发布时间:2023-07-17 20:08:04.0

在我的应用程序中,我想将一些interface 实现fragment
当使用此interface我将其编写为添加listeners ,但会显示错误并且不允许我使用此接口!
我将以下代码写成片段:

public class ServicesFragment extends Fragment implements IabHelper.OnIabSetupFinishedListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_services, container, false);

    public class LoginCheckServiceConnection implements ServiceConnection {

        public void onServiceConnected(ComponentName name, IBinder boundService) {
            service = ILoginCheckService.Stub.asInterface((IBinder) boundService);
            try {
                boolean isLoggedIn = service.isLoggedIn();
                if (isLoggedIn) {
                    iabHelper = new IabHelper(context, bazaarRSA);
                    iabHelper.startSetup(this);
                } else {
                    if (Constants.isPackageInstalled(Constants.BAZAAR_PAYMENT_PACKAGE, packageManager)) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setComponent(new ComponentName(Constants.BAZAAR_PAYMENT_PACKAGE, Constants.BAZAAR_LOGIN_ACTIVITY));
                        startActivity(intent);
                    } else {
                        Toast.makeText(context, "Not installed market on your device", Toast.LENGTH_SHORT).show();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onServiceDisconnected(ComponentName name) {
            service = null;
        }
    }
}

在此代码中: iabHelper.startSetup(this); 当使用this告诉我错误!

我该如何解决?

方法startSetup签名为。

public void startSetup(final OnIabSetupFinishedListener listener)

问题:-您正在传递this ,它将给出直接父类的引用,在这种情况下,该父类是LoginCheckServiceConnection

解决方案:-使用ClassName.this获取外部类引用,因为您的外部类已经实现了OnIabSetupFinishedListener

iabHelper.startSetup(ServicesFragment.this);

如果您在onCreateView()或没有嵌套代码的内部对其进行初始化,则iabHelper.startSetup(this)可以像往常一样隐式提供您的上下文。 在这种情况下,也是直接父类的引用,该类是LoginCheckServiceConnection

但是,如果您深入研究嵌套代码,那么只有this方法不能像往常一样隐式地服务于您的上下文。 为此,您可以显式编写该iabHelper.startSetup(ServicesFragment.this);

  相关解决方案