我有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
答案 0 :(得分:0)
您正在使用应用Context
。这就是为什么你不能把它转换为Activity
。
您可以存储Activity
,而不是存储上下文。或者更好的是,将WeakReference
存储到Activity
。
WeakReference<Activity> weakRef;
Activity activity = weakRef.get();
if(weakRef.get() != null)
{
FragmentManager fm = activity.getFragmentManager();
}