有一个活动中有一个片段,我们称其为FirstFragment。此片段中有一个框架布局,其中包含另一个片段SecondFragment。通过单击SecondFragment,将触发ThirdFragment。在这里,按下后退按钮时,我需要能够返回到SecondFragment。但是,通过单击“后退”按钮,该活动将关闭。这是我的代码:

MainActivity.java

public class MainActivity extends AppCompatActivity{
    ViewPager viewPager;
    String[] titles;
    SecondFragment secondFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentPagerAdapter fragment = new FragmentPagerAdapter(getSupportFragmentManager());
        viewPager = findViewById(R.id.viewPager);

        viewPager.setAdapter(fragment);

        firstFragment = new FirstFragment();

    }

    public class FragmentPagerAdapter extends android.support.v4.app.FragmentPagerAdapter {

        public FragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0 : return FirstFragment.newInstance("hi");
                default: return new OtherFragment();
            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
             getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }
}


FirstFragment.java

public class FirstFragment extends Fragment implements RecyclerViewListener {


    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Fragment secondFragment =SecondFragment.newInstance("hi");
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.frameLayout, secondFragment).commit();



        return inflater.inflate(R.layout.fragment_first, container, false);
    }


    public static FirstFragment newInstance(String text) {

        FirstFragment f = new FirstFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }

    @Override
    public void clicked(int position) {
        Fragment productDetailFragment = ThirdFragment.newInstance(position);
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.add(R.id.frameLayout, productDetailFragment).addToBackStack(null).commit();



        Toast.makeText(getContext(), "pos : " + position, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean longClicked(int position) {
        return false;
    }

}


SecondFragment.java

public class SecondFragment extends Fragment {
    RecyclerView recyclerView;
    static ArrayList<Item> items;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_second, container, false);

        recyclerView = v.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        items = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            Item item = new Item(R.drawable.accept_state, "esm" + i, Integer.toString(i * 100));
            items.add(item);
        }

        recyclerView.setAdapter(new RecylcerViewAdapter(getContext(), (RecyclerViewListener) getParentFragment(), items));


        return v;
    }

    public static SecondFragment newInstance(String text) {

        SecondFragment f = new SecondFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
   }

}


ThirdFragment.java

public class ThirdFragment extends android.support.v4.app.Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment_third, container, false);


        return v;
    }


    public static ThirdFragment newInstance(int position) {

        ThirdFragment f = new ThirdFragment();
        Bundle b = new Bundle();

        f.setArguments(b);

        return f;
    }
}


RecyclerViewListener.java

public interface RecyclerViewListener {
    void clicked(int position);
    boolean longClicked(int position);
}


RecyclerViewAdapter.java

public class RecylcerViewAdapter  extends RecyclerView.Adapter<RecylcerViewAdapter.RecyclerViewHolder>{
    private Context context;
    private RecyclerViewListener recyclerViewListener;
    private ArrayList<Item> items;

    public RecylcerViewAdapter(Context context, RecyclerViewListener recyclerViewListener, ArrayList<Item> items) {
        this.context = context;
        this.recyclerViewListener = recyclerViewListener;
        this.items = items;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        holder.bind(position);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class RecyclerViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView name;
        TextView cost;
        public RecyclerViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    recyclerViewListener.clicked(getAdapterPosition());
                }
            });
            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    return recyclerViewListener.longClicked(getAdapterPosition());
                }
            });
            imageView = itemView.findViewById(R.id.image);
            name = itemView.findViewById(R.id.name);
            cost = itemView.findViewById(R.id.cost);
        }

        public void bind(int position) {
            Item item = items.get(position);
            imageView.setImageResource(item.getImageID());
            name.setText(item.getName());
            cost.setText(item.getCost());
        }
}

}

最佳答案

首先,覆盖onBackPressed(),然后使用use getChildFragmentManager(),如下所示:
    公共无效onBackPressed(){

    // If the fragment exists and has some back-stack entry
    if (myFragment != null && mytFragment.getChildFragmentManager().getBackStackEntryCount() > 0){
        // Get the fragment fragment manager - and pop the backstack
        myFragment.getChildFragmentManager().popBackStack();
    }
    // Else, nothing in the direct fragment back stack
    else{
        // Let super handle the back press
        super.onBackPressed();
    }
}

关于android - 背部在内部 fragment 中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46754352/

10-10 09:02