如何在片段内获取活动参考?

时间:2015-01-10 10:37:24

标签: android dictionary fragment onclicklistener android-fragmentactivity

 myOnClickListener = new MyOnClickListener(getActivity());

我没有在课堂上面获得Activity。我已经实现了Onclick事件,我正在尝试显示Map,但是我没有从Click方法获得任何响应。

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

        }

    }

3 个答案:

答案 0 :(得分:0)

更改

private final Activity activity;

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

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

yourView.setOnClickListener(myOnClickListener);

答案 1 :(得分:0)

尝试上下文:

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

//设置为视图

yourView.setOnClickListener(new myOnClickListener(getActivity));

答案 2 :(得分:0)

初始化此变量表示您的装备类。

private ActivityName mActivityName;

并在名为“ onCreateView”的片段函数中获取该信息

mActivityName = (ActivityName) getActivity();