2

我有三個選項卡。出於測試目的,我將所有三個選項卡設置爲相同的片段.Fragment具有回收站視圖。我只能在第一個片段中查看回收站視圖。無法在多個選項卡中使用回收站視圖

活動代碼:

 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在僅第一標籤可見。如果我滑動選項卡,則僅在第二個選項卡中可見。

我觀察到下面的錯誤,同時調試它:

否適配器連接;跳繩佈局

回答

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

這是非常錯誤的。將您的邏輯從onActivityCreated()轉換爲onViewCreated(),並獲取片段的自己的RecyclerView。每個片段應該在onCreateView()中創建自己的RecyclerView,這將是ViewPager該頁面的內容。

+0

非常感謝..!有效。 10分鐘後會接受答案。 –

相關問題