在Recycler Adapter中使用FragmentManager时,android.app.Application无法强制转换为android.app.Activity

时间:2016-11-26 18:50:12

标签: java android android-context

我有Recycler Adapter类并实现了setOnClickListener来替换片段:

public PlacesAdapter(Context mContext, List<Place> placeList) {
    this.mContext = mContext;
    this.placeList = placeList;
}
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        FragmentManager fm = ((Activity)mContext).getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.mainFragmenLayout, new restaurantsFragment());
        Toast.makeText(mContext, "The place is tapped.", Toast.LENGTH_SHORT).show();
    }
});

我正在使用API​​ 25并且有以下导入:

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

上下文创建如下:

private Context mContext;
public PlacesAdapter(Context mContext, List<Place> placeList) {
    this.mContext = mContext;
    this.placeList = placeList;
}

适配器实例化如下:

adapter = new PlacesAdapter(getActivity().getApplicationContext(), placeList);

但应用程序崩溃并返回以下错误:

  

java.lang.ClassCastException:无法转换android.app.Application   到android.app.Activity

1 个答案:

答案 0 :(得分:0)

您正在使用应用Context。这就是为什么你不能把它转换为Activity

您可以存储Activity,而不是存储上下文。或者更好的是,将WeakReference存储到Activity

WeakReference<Activity> weakRef;

Activity activity = weakRef.get();
if(weakRef.get() != null)
{
    FragmentManager fm = activity.getFragmentManager();
}