2016-05-11 2 views
-2

Я использовал CardView для отображения некоторых данных (данные, отображаемые значения настроек для TextView) .Это CarView прикрепляется к RecyclerView. Отображаемые данные поступают из базы данных и, следовательно, CardView также увеличивается в списке в зависимости от количества строк в базе данных. Я хочу получить данные с определенной Карты по адресу onclick, и я не уверен, как это сделать. и я также удивляюсь, что я использовал одну и ту же карточку для заполнения разных данных, и TextView также имеют одинаковый идентификатор на другой карте. Как достичь этого. Я хочу взять данные onClick, потому что я буду использовать это для редактирования предыдущих данных, изменив его. И мне просто нужен способ получить данные onClick из CardView отдых, который я могу сделать.
Мой код, как: -
MedicationCard:Как получить данные из определенного CardView прикрепленного RecyclerView

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" android:layout_height="match_parent" 

    android:padding="5dp"> 

    <android.support.v7.widget.CardView 
     xmlns:card_view="http://schemas.android.com/apk/res-auto" 
     android:layout_width="match_parent" 
     android:layout_height="200dp" 
     android:elevation="6sp" 
     android:background="@color/colorPrimary" 
     card_view:cardUseCompatPadding="true" 
     android:id="@+id/cardMedview"> 
     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:background="@drawable/bg" 
      android:padding="4dp"> 
      <RelativeLayout 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/NameSection"> 
       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:text="Name:- " 
        android:id="@+id/textView6" 
        android:textColor="#0866C4" 
        android:textStyle="bold" 
        android:layout_alignParentTop="true" 
        android:layout_alignParentStart="true" /> 
       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:text="Name of Med" 
        android:textStyle="bold" 
        android:id="@+id/nameOfUpmingMed" 
        android:layout_alignParentTop="true" 
        android:layout_toEndOf="@+id/textView6" /> 
      </RelativeLayout> 
      <RelativeLayout 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/QuntitySection" 
       android:layout_below="@+id/NameSection" 
       android:layout_alignParentEnd="true" 
       android:layout_alignParentStart="true"> 
       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:textStyle="bold" 
        android:text="Quantity:- " 
        android:textColor="#0866C4" 
        android:id="@+id/textView5" 
        android:layout_alignParentTop="true" 
        android:layout_alignParentStart="true" /> 
       <TextView 
        android:layout_width="100dp" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="crocin" 
        android:layout_marginLeft="3dp" 
        android:id="@+id/QuantOfMed" 
        android:textColor="#000" 
        android:layout_alignParentTop="true" 
        android:layout_toEndOf="@+id/textView5" /> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:textStyle="bold" 
        android:text="Reffil Amount:- " 
        android:id="@+id/textView7" 
        android:textColor="#0866C4" 
        android:layout_marginStart="18dp" 
        android:layout_alignParentTop="true" 
        android:layout_toEndOf="@+id/QuantOfMed" /> 
       <TextView 
        android:layout_width="80dp" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="222" 
        android:textColor="#000" 
        android:id="@+id/ReffilAmt" 
        android:layout_alignParentTop="true" 
        android:layout_toEndOf="@+id/textView7" /> 
      </RelativeLayout> 
      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/expirationSection" 
       android:layout_below="@+id/QuntitySection"> 
       <TextView 
        android:layout_width="wrap_content" 
        android:textStyle="bold" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="Expiration Date:- " 
        android:textColor="#0866C4" 
        android:id="@+id/textView8"/> 
       <TextView 
        android:layout_width="150dp" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="XX/YY/ZZZZ" 
        android:textColor="#000" 
        android:id="@+id/ExpDate" 
        android:layout_marginLeft="3dp" 
        android:layout_alignParentTop="true" 
        android:layout_toEndOf="@+id/textView8" /> 
      </RelativeLayout> 
      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/DaysSection" 
       android:layout_below="@+id/expirationSection"> 
       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginTop="2dp" 
        android:textStyle="bold" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="Days:- " 
        android:textColor="#0866C4" 
        android:id="@+id/textView11" /> 

       <TextView 
        android:layout_width="250dp" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="MON,TUE,WED,THU,FRI,SAT,SUN" 
        android:id="@+id/NoOfDays" 
        android:textColor="#000" 
        android:layout_marginLeft="3dp" 
        android:layout_alignTop="@+id/textView11" 
        android:layout_toEndOf="@+id/textView11" /> 
      </RelativeLayout> 
      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/TimeSection" 
       android:layout_below="@+id/DaysSection"> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:textStyle="bold" 
       android:textAppearance="?android:attr/textAppearanceSmall" 
       android:text="Time:- " 
       android:textColor="#0866C4" 
       android:id="@+id/textView9" 
       /> 

      <TextView 
       android:layout_width="70dp" 
       android:layout_height="wrap_content" 
       android:textAppearance="?android:attr/textAppearanceSmall" 
       android:text="08:00 AM" 
       android:textColor="#000" 
       android:layout_marginLeft="3dp" 
       android:id="@+id/timeMorning" 
       android:layout_alignParentTop="true" 
       android:layout_toEndOf="@+id/textView9" /> 

      <TextView 
       android:layout_width="70dp" 
       android:layout_height="wrap_content" 
       android:textAppearance="?android:attr/textAppearanceSmall" 
       android:text="01:00 PM" 
       android:textColor="#000" 
       android:layout_marginLeft="4dp" 
       android:id="@+id/timeAfternoon" 
       android:layout_alignParentTop="true" 
       android:layout_centerHorizontal="true" /> 

      <TextView 
       android:layout_width="70dp" 
       android:layout_height="wrap_content" 
       android:textAppearance="?android:attr/textAppearanceSmall" 
       android:text="08:00 PM" 
       android:textColor="#000" 
       android:id="@+id/timeEvening" 
       android:layout_alignParentTop="true" 
       android:layout_alignParentEnd="true" 
       android:layout_marginEnd="49dp" /> 
      </RelativeLayout> 
      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:id="@+id/InstructionSection" 
       android:layout_below="@+id/TimeSection"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceSmall" 
        android:text="Instructions:- " 
        android:textColor="#0866C4" 
        android:textStyle="bold" 
        android:layout_marginTop="2dp" 
        android:id="@+id/textView10" 
        /> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="50dp" 
        android:layout_marginTop="2dp" 
        android:textColor="#000" 
        android:text="Take Medicine before bed and after the food.and he shuld take agood sound sleep and shuld wake up early in morning" 
        android:id="@+id/SpecialInst" 
        android:layout_toEndOf="@+id/textView10" /> 

      </RelativeLayout> 



     </RelativeLayout> 

    </android.support.v7.widget.CardView> 



</RelativeLayout> 

Мой фрагмент, который использует RecyclerView для заполнения данных о целях карты.
PrescriptionFragment

public class PrescriptionFragment extends Fragment { 

private Context context; 
    private RecyclerView recyclerView; 
    DatabaseAdaptor databaseAdaptor; 
    public PrescriptionFragment() { 
     // Required empty public constructor 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View view= inflater.inflate(R.layout.fragment_prescription, container, false); 
     recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView); 

     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context); 
     recyclerView.setLayoutManager(linearLayoutManager); 
     context=getActivity(); 
     databaseAdaptor = new DatabaseAdaptor(context); 
     initializeData(); 
     initializeAdapter(); 




     return view; 
    } 

    private void initializeData(){ 
     databaseAdaptor.getDetailData(); 
    } 
    private void initializeAdapter(){ 
     RVAdapter adapter = new RVAdapter(databaseAdaptor.persons); 
     recyclerView.setAdapter(adapter); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     initializeData(); 
     initializeAdapter(); 
    } 
} 

RecyclerViewAdapter:

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


    public static class PersonViewHolder extends RecyclerView.ViewHolder{ 
     CardView cardView; 
     TextView Name,Qunat,refill,expDate,Days,moring,after,evening,inst; 

     public PersonViewHolder(View itemView) { 
      super(itemView); 
      cardView=(CardView)itemView.findViewById(R.id.cardMedview); 
      Name=(TextView)itemView.findViewById(R.id.nameOfUpmingMed); 
      Qunat=(TextView)itemView.findViewById(R.id.QuantOfMed); 
      refill=(TextView)itemView.findViewById(R.id.ReffilAmt); 
      expDate=(TextView)itemView.findViewById(R.id.ExpDate); 
      Days=(TextView)itemView.findViewById(R.id.NoOfDays); 
      moring=(TextView)itemView.findViewById(R.id.timeMorning); 
      after=(TextView)itemView.findViewById(R.id.timeAfternoon); 
      evening=(TextView)itemView.findViewById(R.id.timeEvening); 
      inst=(TextView)itemView.findViewById(R.id.SpecialInst); 
     } 
    } 
    List<Person> persons; 
    RVAdapter(List<Person> persons){ 
     this.persons=persons; 
    } 
    @Override 
    public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
     super.onAttachedToRecyclerView(recyclerView); 
    } 

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

    @Override 
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) { 
     personViewHolder.Name.setText(persons.get(i).name); 
     personViewHolder.Qunat.setText(persons.get(i).qunt); 
     personViewHolder.refill.setText(persons.get(i).refill); 
     personViewHolder.expDate.setText(persons.get(i).date); 
     personViewHolder.Days.setText(persons.get(i).days); 
     personViewHolder.moring.setText(persons.get(i).morning); 
     personViewHolder.after.setText(persons.get(i).after); 
     personViewHolder.evening.setText(persons.get(i).evening); 
     personViewHolder.inst.setText(persons.get(i).inst); 


    } 

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

Person Класс

class Person{ 
    String name,qunt,refill,inst,date,days,morning,after,evening; 
    Person(String name,String quant,String refill,String date,String days,String morn,String Aft,String evening,String inst){ 
     this.name=name; 
     this.qunt=quant; 
     this.refill=refill; 
     this.date=date; 
     this.days=days; 
     this.morning=morn; 
     this.after=Aft; 
     this.evening=evening; 
     this.inst=inst; 
    } 
} 

И, наконец, моя база данных, которая, из которой я заполнение данных.

public List<Person> getDetailData(){ 
     SQLiteDatabase db= helper.getWritableDatabase(); 
     String[] columns={DatabaseHelper.medicationId,DatabaseHelper.medicName,DatabaseHelper.medicationQuant,DatabaseHelper.expirationDate, 
     DatabaseHelper.RiffilAmount,DatabaseHelper.specialInst,DatabaseHelper.alarmDays,DatabaseHelper.timeMorning, 
     DatabaseHelper.timeAfternoon,DatabaseHelper.timeEvening}; 
    Cursor mcursor= db.query(DatabaseHelper.MEDICATION_DETAILS_TABLE, columns, null, null, null, null, null); 
     persons=new ArrayList<>(); 
     StringBuffer buffer=new StringBuffer(); 
     while (mcursor.moveToNext()){ 
     int index1= mcursor.getColumnIndex(DatabaseHelper.medicationId); 
      int index2=mcursor.getColumnIndex(DatabaseHelper.medicName); 
      int index3=mcursor.getColumnIndex(DatabaseHelper.medicationQuant); 
      int index4=mcursor.getColumnIndex(DatabaseHelper.expirationDate); 
      int index5=mcursor.getColumnIndex(DatabaseHelper.RiffilAmount); 
      int index6=mcursor.getColumnIndex(DatabaseHelper.specialInst); 
      int index7=mcursor.getColumnIndex(DatabaseHelper.alarmDays); 
      int index8=mcursor.getColumnIndex(DatabaseHelper.timeMorning); 
      int index9=mcursor.getColumnIndex(DatabaseHelper.timeAfternoon); 
      int index10=mcursor.getColumnIndex(DatabaseHelper.timeEvening); 
      int medid=mcursor.getInt(index1); 
      String name=mcursor.getString(index2); 
      String quant=mcursor.getString(index3); 
      String expDate=mcursor.getString(index4); 
      String refill=mcursor.getString(index5); 
      String specialInst=mcursor.getString(index6); 
      String alarmdays=mcursor.getString(index7); 
      String timemorning=mcursor.getString(index8); 
      String timeafter=mcursor.getString(index9); 
      String timeevening= mcursor.getString(index10); 
      persons.add(new Person(name,quant,refill,expDate,alarmdays,timemorning,timeafter,timeevening,specialInst)); 

     } 
     mcursor.close(); 
     db.close(); 
     return persons; 
    } 

И мое O/P как: enter image description here

+0

Установите прослушиватель кликов в RecyclerView и получите данные по выбранному элементу (позиции). Вы можете увидеть пример здесь, чтобы добавить [на клик-прослушиватель] (http: // antonioleiva.com/recyclerview-listenener /) –

+0

ok будет изучать это. почему я был заблокирован, я спросил что-то не так? –

+0

Не знаю. Иногда я не понимаю, почему кто-то отказался. Возможно, они думают, что вы можете найти эту проблему. –

ответ

0

Этот CardView прикрепляется к RecyclerView. Для получения данных из любого CardView вам просто нужно получить позицию элемента, который извлекается из позиции RecyclerView. Yo могут читать этот ответ: RecyclerView ItemClickListener

+0

Спасибо за ссылку. –

0

Я новичок в разработке Android, но нашел что-то интересное ...

My screen looks as below...

Итак, У меня есть RecyclerView и сочетание CardView, и каждый элемент будет иметь панель инструментов, прикрепленную к ней ...

Итак, если я реализую Toolbar.OnMenuItemClickListener, наряду с определением вашего класса ViewHolder, он должен решить проблему.

Примечание. Даже если вы не хотите использовать панель инструментов, тогда используйте View.OnClickListener вместе с классом ViewHolder и реализуйте событие OnClick, и я думаю, что это будет трюк.

Here is the rest of my ViewHolder class definition...

Надежда Это помогает !!!

+0

спасибо, я уже разработал свое приложение, и я сделал кое-что похожее на ваше предложение и смог долго решить мою проблему. Спасибо, в любом случае –

Смежные вопросы