Android:处理程序的访问活动

时间:2012-08-17 09:41:24

标签: android

我有以下处理程序:

public class SiteListener implements OnItemClickListener{
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    }
}

我希望能够拨打以下电话:

myActivity.getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.site_info, siteInfoFragment)
            .commit();

如何从SiteListener获取对活动的访问权限?有没有办法使用adapterView

2 个答案:

答案 0 :(得分:3)

在创建活动时将活动的引用传递给SiteListener

编辑添加代码示例:

public class SiteListener implements OnItemClickListener{
    private MyActivity myActivity;

    public SiteListener(MyActivity myActivity) {
        this.myActivity = myActivity;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        myActivity.getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.site_info, siteInfoFragment)
            .commit();

    }
}

答案 1 :(得分:1)

您可以使用FragmentActivity投射view以获取FragmentActivity的实例。

FragmentActivity activity = ((FragmentActivity)view.getContext());
activity.getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.site_info, siteInfoFragment)
            .commit();