如何无意间将数据从适配器传递到活动

时间:2019-12-21 04:09:15

标签: android android-recyclerview recycler-adapter

我尝试不使用意图就将值从适配器传递给活动。当我单击recyclerview时,数据应存储到activity。下面是我的代码

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();
    }
}

3 个答案:

答案 0 :(得分:0)

您似乎正在传递应用程序上下文,而不是传递上面代码中实现getConnection();的活动,您只需要进行以下更改。

TimeAdapter.AdapterCallback

答案 1 :(得分:0)

您可以将回调更改为:

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

并按以下方式调用它:

mAdapterCallback.onMethodCallback(times.get(position).toString());

答案 2 :(得分:0)

在活动类中定义一个带有参数的方法,并通过将值作为参数传递来从适配器类中调用此方法。