无法在多个选项卡中使用回收站视图

时间:2015-12-29 19:50:31

标签: android android-fragments android-recyclerview android-tabs

我有三个标签。出于测试目的,我将相同的片段设置为所有三个标签。片段具有循环器视图。我只能在第一个片段中查看回收者视图。

活动代码:

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new TrialsFragment(), getString(R.string.camps));
        adapter.addFragment(new TrialsFragment(), getString(R.string.trials));
        adapter.addFragment(new TrialsFragment(), getString(R.string.events));
        viewPager.setAdapter(adapter);

片段代码:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler);
        adapter = new TrialsRecyclerViewAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
    }

适配器代码:

public class TrialsRecyclerViewAdapter extends RecyclerView.Adapter<TrialsRecyclerViewAdapter.ViewHolder> {

    String[] names = {"Sample Name","Sample Name","Sample Name","Sample Name","Sample Name"};
    String[] regNos ={"12345678","12345678","12345678","12345678","12345678"};

    @Override
    public TrialsRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        CardView cv = (CardView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.trial_card, parent, false);
        return new ViewHolder(cv);
    }

    @Override
    public void onBindViewHolder(TrialsRecyclerViewAdapter.ViewHolder holder, int position) {
        final CardView cardView = holder.cardView;

        TextView name = (TextView)cardView.findViewById(R.id.trial_name);
        TextView regNumber = (TextView)cardView.findViewById(R.id.trial_start_end);
        name.setText(names[position]);
        regNumber.setText(regNos[position]);

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    @Override
    public int getItemCount() {
        return names.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        private CardView cardView;
        public ViewHolder(CardView v)
        {
            super(v);
            cardView = v;
        }
    }
}

活动开始后,RecyclerView仅在第一个标签中可见。如果我滑动标签,则仅在第二个标签中显示。

我在调试时发现了以下错误:

  

没有连接适配器;跳过布局

1 个答案:

答案 0 :(得分:4)

recyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler);

这是非常错误的。将您的逻辑从onActivityCreated()移至onViewCreated(),然后获取片段的拥有 RecyclerView。每个片段都应在RecyclerView中创建自己的onCreateView(),这将是ViewPager页面的内容。