Я пытаюсь передать значение от адаптера к деятельности без использования намерения. когда я нажимаю на просмотрщик данных, данные должны быть сохранены в активность. ниже мой код

Activity.java

public class BookingCalender extends AppCompatActivity implements ItemClickListener, TimeAdapter.AdapterCallback {
    TextView userphone,username,txt_from_date,txt_end_date;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager timeLayoutManager;
    private RecyclerView.Adapter adapter;

    String time,date="";
    ArrayList<String> times;
    private MaterialCalendarView calendarView;
    private TextView selectedDateTv;
    private String start_time="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_booking_calender);
        //Init

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_timeSlots);
        recyclerView.setHasFixedSize(true);
        timeLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(timeLayoutManager);


        txt_from_date=(TextView)findViewById(R.id.txt_from_date);

        txt_end_date=(TextView)findViewById(R.id.txt_to_date);

        //Initialize CustomCalendarView from layout
        calendarView = (MaterialCalendarView) findViewById(R.id.calendarView);

        calendarView.setSelectionColor(Color.parseColor("#7EA2FA"));

        try {
            getCurrentDateandTime();
            getCurrentTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }


        times = new ArrayList<String>();
        Calendar calender = Calendar.getInstance();

        calender.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));

        int ti = calender.get(Calendar.HOUR_OF_DAY);
        int minutes = calender.get(Calendar.MINUTE);

        System.out.println(minutes);
        //int hourInTime=String.valueOf(ti);
        String[] quarterHours = {
                "00",
                "15",
                "30",
                "45"
        };
        boolean isflag = false;

        ti=9;
        times = new ArrayList < > ();

        for (int i = ti; i < 22; i++) {
            if(ti==9) {

                for (int j = 0; j < 4; j++) {

                    if ((i == ti && minutes < Integer.parseInt(quarterHours[j])) || ( i!=ti)|| isflag == true) {

                        isflag = true;
                        String time = i + ":" + quarterHours[j];
                        if (i < 10) {
                            time = "0" + time;
                        }
                        times.add("Today " + time);
                    }
                }
            }
        }
        VehicleViewHolder vehicleViewHolder = null;


        String one="";
        adapter = new TimeAdapter(times, getApplicationContext(),one);
    //    Toast.makeText(BookingCalender.this,"Selected Time is :"+one,Toast.LENGTH_LONG).show();

        recyclerView.setAdapter(adapter);


        calendarView.addDecorator(new PrimeBeforeDayDisableDecorator());
        calendarView.addDecorator(new PrimeAfterDayDisableDecorator());



        MaterialCalendarView materialCalView = findViewById(R.id.calendarView);
        materialCalView.setDateSelected(CalendarDay.today(), true);

       // Toast.makeText(BookingCalender.this,"Clicked"+one,Toast.LENGTH_LONG).show();
    }

    private void getCurrentTime() {

        DateFormat df = new SimpleDateFormat("HH:mm a");
        time = df.format(Calendar.getInstance().getTime());

    //    Toast.makeText(BookingCalender.this,""+date,Toast.LENGTH_LONG).show();
    }


    private void getCurrentDateandTime() throws ParseException {

        date = new SimpleDateFormat("dd MMM").format(new Date());


    }


    @Override
    public void onClick(View view, int position, boolean isLongClick) {

        Toast.makeText(BookingCalender.this,"Hi",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(int position) {

        Toast.makeText(BookingCalender.this,"Hi",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View.OnClickListener onClickListener) {

        Toast.makeText(BookingCalender.this,"Hi",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMethodCallback() {

        Toast.makeText(BookingCalender.this,"Hi",Toast.LENGTH_LONG).show();

    }


    private static class PrimeBeforeDayDisableDecorator implements DayViewDecorator {

        @Override
        public boolean shouldDecorate(final CalendarDay day) {
            CalendarDay date = CalendarDay.today();
            return (day.isBefore(date)) ? true : false;
        }

        @Override
        public void decorate(final DayViewFacade view) {
            view.setDaysDisabled(true);
        }


    }
    private static class PrimeAfterDayDisableDecorator implements DayViewDecorator {

        @Override
        public boolean shouldDecorate(final CalendarDay day) {
            CalendarDay date = CalendarDay.today();
            return (day.isAfter(date)) ? true : false;
        }



        @Override
        public void decorate(final DayViewFacade view) {
            view.setDaysDisabled(true);
          //  view.setBackgroundDrawable(ContextCompat.getDrawable(PrimeAfterDayDisableDecorator.this,R.co));

          //  view.addSpan(new BackgroundColorSpan(Color.rgb(0,0,255)));
        }
    }
}

Adapter.java

public class TimeAdapter extends RecyclerView.Adapter<TimeAdapter.TimeViewHolder> {

    private AdapterCallback mAdapterCallback;
    ArrayList<String> times;

    private  Context context;
    String start_time="";

    public String getStart_time() {
        return start_time;
    }

    public void setStart_time(String start_time) {
        this.start_time = start_time;
    }

    public TimeAdapter(ArrayList<String> times, Context context, String start_time) {
        this.times = times;
        this.context = context;
        this.start_time = start_time;
        try {
            this.mAdapterCallback = ((AdapterCallback) context);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.");
        }
    }

    @Override
    public TimeAdapter.TimeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.time_slot_layout, parent, false);
        TimeViewHolder viewHolder = new TimeViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final TimeAdapter.TimeViewHolder holder, final int position) {

        holder.text_time.setText(times.get(position).toString());



        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                start_time=times.get(position).toString();

                mAdapterCallback.onMethodCallback();
                //itemClickListener.onItemClick(position);


           //   holder.itemClickListener.onClick(position);


             //   Toast.makeText(v.getContext(),"Selected Time is :"+times.get(position).toString(),Toast.LENGTH_LONG).show();
            }
        });


    }

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

    public static class TimeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ItemClickListener itemClickListener;

        protected TextView text_time;


        //  private ItemClickListener itemClickListener;
        public TimeViewHolder(View itemView) {
            super(itemView);



            text_time = (TextView) itemView.findViewById(R.id.time_slot);


            itemView.setOnClickListener(this);

        }

        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener = itemClickListener;
        }

        @Override
        public void onClick(View v) {

            itemClickListener.onClick(v, getAdapterPosition(), false);

        }

    }
    public static interface AdapterCallback {
        void onMethodCallback();
    }
}
-1
Karthick Jai 21 Дек 2019 в 07:09

3 ответа

Похоже, что вы передаете контекст приложения вместо действия, которое реализует TimeAdapter.AdapterCallback в приведенном выше коде, вам просто нужно сделать следующие изменения.

adapter = new TimeAdapter(times, this ,one);
0
Sai 21 Дек 2019 в 07:44

Вы можете изменить свой обратный вызов на:

 public static interface AdapterCallback {
    void onMethodCallback(String data);
}

И назовите это как ниже:

mAdapterCallback.onMethodCallback(times.get(position).toString());
0
Haniyeh Ehsaninejad 21 Дек 2019 в 11:51

В классе деятельности определите метод с параметрами и вызовите этот метод из класса адаптера, передавая значения в качестве параметров.

0
aswathy gopi 21 Дек 2019 в 13:52