0

我有以下处理程序:

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

4

2 回答 2

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

    }
}
于 2012-08-17T09:52:17.920 回答
1

您可以FragmentActivity使用view来获取FragmentActivity.

FragmentActivity activity = ((FragmentActivity)view.getContext());
activity.getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.site_info, siteInfoFragment)
            .commit();
于 2012-08-17T09:46:24.100 回答