如何在片段中获取 activity 引用?

How to get activity reference inside fragment?

 myOnClickListener = new MyOnClickListener(getActivity());

我没有在 class 上面得到 Activity。我已经实现了 Onclick 事件,我试图在其中显示地图,但我没有从点击方法获得任何响应。

private static class MyOnClickListener implements View.OnClickListener {

        private final Context context;

        private MyOnClickListener(Context context) {
            this.context = context;
        }

        @Override
        public void onClick(View v) {
                String label = "ABC Label";
                String uriBegin = "geo:" + myAdapter.sendLati() + "," + myAdapter.sendLongi();
                String query = myAdapter.sendLati() + "," + myAdapter.sendLongi()  + "(" + label + ")";
                String encodedQuery = Uri.encode(query);
                String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
                Uri uri = Uri.parse(uriString);
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
                 startActivity(intent);

        }

    }

改变

private final Activity activity;

private MyOnClickListener(Activity activity) {
     this.activity= activity;
}

完成此操作后,将此侦听器设置为您的视图

yourView.setOnClickListener(myOnClickListener);

尝试使用上下文:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
context.startActivity(intent);

//设置为视图

yourView.setOnClickListener(new myOnClickListener(getActivity));

在您的片段中初始化此变量 class。

private ActivityName mActivityName;

并在名为 "onCreateView"

的片段函数中像这样获取它
mActivityName = (ActivityName) getActivity();