6

Questa è una sorta di follow-up o complemento a this post. Sto cercando di ottenere la posizione di un oggetto nel mio RecyclerView, ma nessuno dei metodi che ho provato ha funzionato.getAdapterPosition() non restituisce la posizione dell'elemento in RecyclerView

Ho chiamato getAdapterPosition() nel mio costruttore PersonViewHolder e assegnato il suo valore alla posizione intera, che viene utilizzata nella classe UnitOneFragment per eseguire un'azione di conseguenza (vedere metodo onClick()). Ma qualunque cosa sia, non succede e la mia ipotesi è perché il metodo getAdapterPosition() non funziona o non viene usato correttamente.

mio adattatore:

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> { 

Context mContext; 

RVAdapter(Context context, List<Chapter> chapters) { 
    mContext = context; 
    this.chapters = chapters; 
} 

public static CardView cv; 
public static int position; 
public static String chapterNumberTitle; 

public class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { 
    TextView chapterName; 
    TextView chapterNumber; 
    // ImageView chapterPhoto; 

    public PersonViewHolder(View itemView) { 
     super(itemView); 

     cv = (CardView) itemView.findViewById(R.id.cv); 
     chapterName = (TextView) itemView.findViewById(R.id.chapter_name); 
     chapterNumber = (TextView) itemView.findViewById(R.id.chapter_number); 
     // chapterPhoto = (ImageView) itemView.findViewById(R.id.person_photo); 

     chapterNumberTitle = chapterNumber.getText().toString(); 
     position = getAdapterPosition(); 

     itemView.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     UnitOneFragment.chapterChecker(); 

     Intent intent = new Intent(mContext, ChapterActivity.class); 
     mContext.startActivity(intent); 
    } 
} 

List<Chapter> chapters; 

@Override 
public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
    super.onAttachedToRecyclerView(recyclerView); 
} 

@Override 
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 
    View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false); 
    PersonViewHolder pvh = new PersonViewHolder(v); 
    return pvh; 
} 

@Override 
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) { 
    personViewHolder.chapterName.setText(chapters.get(i).chapterName); 
    personViewHolder.chapterNumber.setText(chapters.get(i).chapterNumber); 
    // personViewHolder.chapterPhoto.setImageResource(persons.get(i).photoId); 

} 

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

L'altra classe:

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

private List<Chapter> chapters; 
private RecyclerView rv; 
private RecyclerView.LayoutManager llm; 

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


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View v = inflater.inflate(R.layout.fragment_unit_one, container, false); 

    getActivity().setTitle("Unit One"); 

    rv = (RecyclerView) v.findViewById(R.id.rv); 
    rv.setHasFixedSize(true); 

    llm = new LinearLayoutManager(getActivity()); 
    rv.setLayoutManager(llm); 

    initializeData(); 
    initializeAdapter(); 

    return v; 
} 

private void initializeData() { 
    chapters = new ArrayList<>(); 
    chapters.add(new Chapter("Human Prehistory to the Early Civilizations", "Chapter One")); 
    chapters.add(new Chapter("Classical China", "Chapter Two")); 
    chapters.add(new Chapter("Classical India", "Chapter Three")); 
    chapters.add(new Chapter("Classical Greece and Rome", "Chapter Four")); 
    chapters.add(new Chapter("Classical Period: Declines and Diversities", "Chapter Five")); 
} 

private void initializeAdapter() { 
    RVAdapter adapter = new RVAdapter(getActivity(), chapters); 
    rv.setAdapter(adapter); 
} 

public static void chapterChecker() { 

    if (RVAdapter.position == 0) { 
     SummaryFragment.summaryText.setText("Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32."); 
     } 
    } 
} 

class Chapter { 
String chapterName; 
String chapterNumber; 
// int photoId; 

Chapter(String chaptername, String chapternumber) { 
    this.chapterName = chaptername; 
    this.chapterNumber = chapternumber; 
    // this.photoId = photoId; 
    } 
} 

Il mio codice sembra abbastanza auto-esplicativo, ma se c'è qualcosa di poco chiaro, per favore fatemelo sapere e io aggiungerà ulteriori informazioni. Ancora una volta, il problema è che non riesco a ottenere la posizione dell'elemento in RecyclerView e quindi agire su di esso.

risposta

14

chiamata getAdapterPosition a vostra metodo onClick perché poi al momento del click u vogliono conoscere la posizione della voce. Se controlli al momento della creazione, sarà (il più delle volte) impreciso.

+5

Puoi fornire un codice e mostrarmi come sarebbe, per favore? – wasimsandhu

+1

Ecco l'esempio di codice che hai chiesto :) https://gist.github.com/a9595/f8169a0d99c6c5be747b53b34976364f – tieorange

+4

@tieorange: Il link gist dice che la pagina non è stata trovata. Si prega di aggiornare quello corretto qui in modo che ci hep noi. – Madhan

Problemi correlati