我想从Adapter Class调用Fragment但不能这样做.. 所以请一些方法来调用片段。我有一个第一次调用活动的方法,然后切换片段是否有任何其他方法
以下是代码:
public class FanAdapter extends RecyclerView.Adapter<FanAdapter.MyViewHolder>
{
private Context mContext;
private List<Fan> FanList;
public class MyViewHolder extends RecyclerView.ViewHolder
{
public TextView testTitle;
public CardView mCardView;
public MyViewHolder(View view)
{
super(view);
mCardView = (CardView) view.findViewById(R.id.card_view);
testTitle = (TextView) view.findViewById(R.id.fan_name);
}
}
public FanAdapter(Context mContext, List<Fan> FanList)
{
this.mContext = mContext;
this.FanList = FanList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fanslist, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Fan album = FanList.get(position);
holder.testTitle.setText(album.getName());
holder.mCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Slecteditem= String.valueOf(position);
Bitmap bmp = BitmapFactory.decodeResource(Resources.getSystem(), position);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Fragment fragment = new ProfileDisplay();
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);
fragmentTransaction.replace(R.id.fl_toplayout, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Toast.makeText(mContext,"Profile"+album.getName(),Toast.LENGTH_LONG).show();
}
});
// loading album cover using Glide library
}
@Override
public int getItemCount()
{
return FanList.size();
}
}
编辑器无法解决
中的getActivity()方法 FragmentManager fm = getActivity().getFragmentManager();
答案 0 :(得分:0)
将mContext
传递给getFragmentManager();
。将mContext
投射到Activity
。
像这样。
FragmentManager fm = (Activity)mContext.getFragmentManager();
答案 1 :(得分:0)
更好的方法是使用接口来通知调用适配器的类。
这样的事情:
public interface NotifyChange {
void onItemClicked();
}
然后在onItemClicked()中执行操作,想要实现。
答案 2 :(得分:-1)
使用此代码替换适配器类中的片段;
Fragment fragment = new YourFragmentName();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
Bundle args = new Bundle();
args.putString("itemname", Slecteditem);
args.putByteArray("picture", byteArray);
fragment.setArguments(args);