从带有开关盒的片段打开新片段

时间:2017-11-23 08:12:22

标签: android android-fragments

我将使用RecyclerView switch case intent从当前片段(1)测试移动到新的片段布局(2)。 但它不起作用并保持当前片段。

FragmentAdapter.java

public ViewHolder(View itemView) {
            super(itemView);
            context = itemView.getContext();
            tvTitle = (TextView)itemView.findViewById(R.id.tvTitle);
            tvDesc = (TextView)itemView.findViewById(R.id.tvDesc);
            tvImage = (ImageView)itemView.findViewById(R.id.tvImage);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Intent intent;
                    switch (getAdapterPosition()) {

                        case 0:
                            intent = new Intent(context, FragmentTwo.class);
                            break;

                        case 1:
                            intent = new Intent(context, FragmentThree.class);
                            break;

                        default:
                            intent = new Intent(context, FragmentHome.class);
                            break;
                    }
                    context.startActivity(intent);
                }
            });
        }

任何想法?三江源

1 个答案:

答案 0 :(得分:1)

在ViewHolder中声明并初始化Context

public ViewHolder(View itemView) {
    super(itemView);
    final Context context = itemView.getContext();

如果加载recyclerview的片段的Activity扩展了Activity

,请添加以下方法
private void loadFragment(Context context, Fragment fragment) {
    ((Activity) context).getFragmentManager()
                 .beginTransaction()
                 .replace(R.id.frame_layout, fragment)
                 .addToBackStack(fragment.getTag())
                 .commit();

如果加载recyclerview的片段的Activity扩展了AppCompatActivity

,请添加以下方法
private void loadFragment(Context context, Fragment fragment) {
    ((AppCompatActivity) context).getSupportFragmentManager()
                 .beginTransaction()
                 .replace(R.id.frame_layout, fragment)
                 .addToBackStack(fragment.getTag())
                 .commit(); 

在开关案例中加载您选择的片段

switch(getAdapterPosition()) {
     case 0:
          loadFragment(context, new YourFragment());
        break;
     case 1:
          loadFragment(context, new YourFragment());
        break;
     case 2:
          loadFragment(context, new YourFragment());
        break;
     default:
          loadFragment(context, new YourFragment());
        break;
}