第二次访问时,Recyclerview中的隐藏位置出现

时间:2016-10-20 02:04:50

标签: android android-recyclerview gridlayoutmanager

我使用RecyclerView通过GridLayoutManager创建了一个巴士座位布局。 当视图第一次膨胀时,seat arrangement view, 仅显示可见的适配器位置,但是当视图在同一会话{@ 3}}中下次膨胀时,所有适配器位置都可见。 应该怎么做才能消除这个错误?

1 个答案:

答案 0 :(得分:0)

//This is the seat selection activity

package com.anbocas.fleet;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.StringTokenizer;

import static com.anbocas.fleet.SeatAdapter.*;

public class SeatSelectionActivity extends AppCompatActivity {

    ArrayList<Integer> items = new ArrayList<>(); // contains values 0 for hidden seat and 1 for visible seats
    ArrayList<BusSeatDataProvider> dataProvider = new ArrayList<>();
    ArrayList<Integer> seatNos = new ArrayList<>(); // this is not used
    static int hidePos = 3;
    int item = 1;
    final int TOTAL_SEATS = 50;
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    GridLayoutManager gridLayoutManager;
    Bitmap seatIcon;
    ArrayList<Integer> seatsJSONed = new ArrayList<>(); // contain booked seats available in database
    ArrayList<Integer> seatsPosJSONed = new ArrayList<>(); // contains the adapter position of the booked seats
    private TextView seatSelected;
    private TextView Totalfare;
    SeatAdapter seat;
    Button MakePayment;
    // ArrayList<String> seat_select = new ArrayList<>();
    String seatsFetched = "";
    static String seats = "";
    static String seatsPos="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seat_selection);
        seatsFetched = getIntent().getStringExtra("seatsFetchedJSON");// JSON of seats and adapter position
        seatIcon = BitmapFactory.decodeResource(this.getResources(), R.drawable.seat_available_24dp);

        seatSelected = (TextView) findViewById(R.id.tv_seatSelected);
        Totalfare = (TextView) findViewById(R.id.tv_totalFare);
        MakePayment = (Button) findViewById(R.id.btn_makePayment);
        recyclerView = (RecyclerView) findViewById(R.id.seatRecycler);
        recyclerView.setHasFixedSize(true);
        gridLayoutManager = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(gridLayoutManager);

        //---------------------------------------------------------------
        JSONObject jsonObject;
        //Log.e("seatsFetched",seatsFetched);
        Toast.makeText(this, seatsFetched, Toast.LENGTH_LONG).show();
        try {

            jsonObject = new JSONObject(seatsFetched);

            JSONArray jsonArray = jsonObject.getJSONArray("seatsFetched");

            JSONObject final_object;
            for (int i = 0; i < jsonArray.length(); i++) {
                final_object = jsonArray.getJSONObject(i);
                seats = final_object.getString("seats"); //booked seats extracted from json
                seatsPos=final_object.getString("seatPos");// adapter position extracted from json
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        StringTokenizer st = new StringTokenizer(seats,",");
        StringTokenizer st1=new StringTokenizer(seatsPos,",");
       int i;
        while (st.hasMoreTokens()) {
            String seat=st.nextToken();
            seatsJSONed.add(Integer.parseInt(seat));// extracting & adding individual seats to integer arraylist
        }
        while (st1.hasMoreTokens()) {
            String seatP=st1.nextToken();
            seatsPosJSONed.add(Integer.parseInt(seatP));// extracting and adding individual adapter position to integer arraylist
        }

        //-----------------------------------------------------------


        for (i = 1; i <=TOTAL_SEATS; i++) {
            if (i == hidePos && hidePos <= 43) {

                items.add(0);
                //item--;
                hidePos = hidePos + 5;
                seatNos.add(null);
                Log.e("itemValueWhereHide", item + "-" + i);
                dataProvider.add(new BusSeatDataProvider(null, null, false));
                adapter.notifyDataSetChanged();
            } else if (i == 48) {
                items.add(1);
                seatNos.add(item);
                Log.e("itemValue", (item) + "-" + i);
                dataProvider.add(new BusSeatDataProvider(seatIcon, item + "", false));
                adapter.notifyDataSetChanged();

            } else if (i == 49) {
                items.add(1);
                item = item + 1;
                seatNos.add(item);
                Log.e("itemValue", (item) + "-" + i);
                dataProvider.add(new BusSeatDataProvider(seatIcon, item + "", false));
                adapter.notifyDataSetChanged();
            } else if (i == 50) {
                items.add(1);
                item = item + 1;
                seatNos.add(item);
                Log.e("itemValue", (item) + "-" + i);
                dataProvider.add(new BusSeatDataProvider(seatIcon, item + "", false));
                adapter.notifyDataSetChanged();
            } else {
                items.add(1);
                seatNos.add(item);
                Log.e("itemValue", item + "-" + i);
                dataProvider.add(new BusSeatDataProvider(seatIcon, item + "", false));
                adapter.notifyDataSetChanged();
                item++;

            }
        }
        adapter = new SeatAdapter(dataProvider, items, seatNos, this, seatSelected, Totalfare,seatsJSONed,seatsPosJSONed);
        recyclerView.setAdapter(adapter);


    }

    public void onProceedClick(View view) {
        seat = new SeatAdapter();
        Intent intent = new Intent(this, PassengerDetailsActivity.class);
        Log.e("NumOfSeatsBooked", seat.seatCounter + "");
        intent.putExtra("NumOfSeatsBooked", seat.seatCounter);
        Log.e("seats", seatSelected.getText().toString());
        intent.putExtra("seatsSelected", seatSelected.getText().toString());
        Toast.makeText(this,seat.seat_position,Toast.LENGTH_SHORT).show();
        intent.putExtra("seatsSelectedPosition", seat.seat_position);
        // tokenize this seats string and send to passengerdetails activity to link each seat with the passenger
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        adapter.notifyDataSetChanged();
    }
}


// This is Seat Adapter
package com.anbocas.fleet;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rahul Gupta on 06/09/2016.
 */
public class SeatAdapter extends RecyclerView.Adapter<SeatAdapter.ViewHolder> {

    ArrayList<BusSeatDataProvider> arrayList = new ArrayList<BusSeatDataProvider>();
    ArrayList<Integer> seatNos = new ArrayList<Integer>();
    ArrayList<Integer> items = new ArrayList<>();
    ArrayList<String> seat_select = new ArrayList<>();
    static ArrayList<String> seat_pos = new ArrayList<>();
    static String seat_position;
    BusSeatDataProvider dataProvider;
    BusSeatDataProvider dataProvider1;
    BusSeatDataProvider item;
    Context context;
    LinearLayout singleSeat;
    Bitmap seatIcon;
    Bitmap seatSelect, seatUnav;
    int fare = 0;
    static int count=0;
    static int seatCounter = 0;
    SeatSelectionActivity ob;
    String seats = "";
    TextView seatSelected, Totalfare;
    ArrayList<Integer> seatsJSONed= new ArrayList<>();
    ArrayList<Integer> seatsPosJSONed= new ArrayList<>();

    public SeatAdapter(ArrayList<BusSeatDataProvider> arrayList, ArrayList<Integer> items, ArrayList<Integer> seatNos, Context context,
                       TextView seatSelected, TextView Totalfare, ArrayList<Integer> seatsJSONed, ArrayList<Integer> seatsPosJSONed) {
        this.arrayList = arrayList;
        this.context = context;
        this.items = items;
        this.seatNos = seatNos;
        this.seatSelected = seatSelected;
        this.Totalfare = Totalfare;
        seatUnav = BitmapFactory.decodeResource(context.getResources(), R.drawable.seat_unavailable_24dp);
        seatIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.seat_available_24dp);
        seatSelect = BitmapFactory.decodeResource(context.getResources(), R.drawable.seat_selected_24dp);
        //ob=new SeatSelectionActivity();
        this.seatsJSONed = seatsJSONed;
        this.seatsPosJSONed = seatsPosJSONed;
    }

    public SeatAdapter() {
//
    }

    @Override
    public SeatAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_view_single, parent, false);
        final ViewHolder viewHolder = new ViewHolder(v);
        singleSeat=(LinearLayout)v.findViewById(R.id.single_seat_layout);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final SeatAdapter.ViewHolder holder, final int position) {
        holder.setIsRecyclable(false);
        //-----------------------------------------------------------
        if (items.get(position) == 0) {
            dataProvider = arrayList.get(position);
            //holder.seatIcon.setImageBitmap(dataProvider.getSeatIcon());
            //holder.seatNo.setText(dataProvider.getSeatNo());
            holder.seatIconn.setVisibility(View.INVISIBLE);
            holder.seatNo.setVisibility(View.INVISIBLE);
            holder.seatIconn.setClickable(false);
            holder.seatNo.setClickable(false);
        } else {
            dataProvider = arrayList.get(position);
            holder.seatIconn.setImageBitmap(dataProvider.getSeatIcon());
            holder.seatNo.setText(dataProvider.getSeatNo());
            if(count<seatsJSONed.size())

            {
                for (int i = 0; i < seatsJSONed.size(); i++) {

                    count++;
                    int p = seatsPosJSONed.get(i);
                    System.out.println(seatsJSONed.get(i));
                    System.out.println(seatsPosJSONed.get(i));
                    arrayList.set(p, new BusSeatDataProvider(seatUnav,seatsJSONed.get(i)+"", true));
                    holder.seatIconn.setClickable(false);
                    holder.seatNo.setClickable(false);
                    holder.seatIconn.setEnabled(false);
                    holder.seatIconn.setFocusable(false);
                    singleSeat.setClickable(false);
                }
            }


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

                    if (items.get(position) == 1) {
                        item = arrayList.get(position);
                    }

                    Bitmap seatcompare = item.getSeatIcon();
                    boolean seatCompareResult;//=seatCompareResult(seatcompare,seatIcon);
                    seatCompareResult = seatcompare.sameAs(seatIcon);
                    if (seatCompareResult == true) {
//                        Log.e("beforeMethod", "true");
                        seatSelected(position);
//                        Log.e("AfterMethod", "true");
                    } else {
//                        Log.e("beforeMethod", "true");
                        seatDeselected(position);
//                        Log.e("AfterMethod", "true");

                    }
                }


                public void seatSelected(int pos) {
                    if (items.get(pos) == 1) {
                        dataProvider1 = arrayList.get(pos);
                    }
                    if (seatCounter < 6) {
                        arrayList.remove(pos);
                        int i = pos;
                        seatCounter++;
//                        Log.e("SeatSelect", "true");
//                    Log.e("BeforeNotify", "true");
//                        Log.e("seatCounter", seatCounter + "");
                        arrayList.add(i, new BusSeatDataProvider(seatSelect, dataProvider1.getSeatNo(), true));
                        notifyDataSetChanged();
//                        Log.e("AfterNotify", "true");
                        //seats = seats + "" + (i) + ",";
                        seat_select.add(dataProvider1.getSeatNo());
                        //add positions to arraylist for the seat selected
                        seat_pos.add(pos + "");
                        seats = TextUtils.join(",", seat_select).toString();
                        //concatenate the selected seat position to form a string
                        seat_position = TextUtils.join(",", seat_pos).toString();
                        Toast.makeText(context, seat_position, Toast.LENGTH_SHORT).show();
                        seatSelected.setText(seats);
                        fare = fare + 330;
                        Totalfare.setText(String.valueOf(fare));
                    } else {
                        Toast.makeText(context, "Can't book more than 6 seats at a time!", Toast.LENGTH_SHORT).show();
                    }
                }

                public void seatDeselected(int pos) {
                    if (items.get(pos) == 1) {
                        dataProvider1 = arrayList.get(pos);
                    }
                    arrayList.remove(pos);
                    seat_select.remove(dataProvider1.getSeatNo());
                    seat_pos.remove(pos + "");
                    int i = pos;
                    seatCounter--;
//                    Log.e("SeatDeSelect", "true");
//                    Log.e("BeforeNotify", "true");
//                    Log.e("seatCounter", seatCounter + "");
                    arrayList.add(i, new BusSeatDataProvider(seatIcon, dataProvider1.getSeatNo(), false));
                    notifyDataSetChanged();
//                    Log.e("AfterNotify", "true");
                    seats = TextUtils.join(",", seat_select).toString();
                    seat_position = TextUtils.join(",", seat_pos).toString();
                    Toast.makeText(context, seat_position, Toast.LENGTH_SHORT).show();
//                    seats = seats.replace("" + dataProvider1.getSeatNo() + ",", "");
                    fare = fare - 330;
                    Totalfare.setText(fare + "");
                    seatSelected.setText(seats);

                }
            });
        }
    }

//     boolean seatCompareResult(Bitmap seatcompare, Bitmap seatIcon) {
//
//        {
//            if (seatcompare.getHeight() != seatIcon.getHeight())
//                return false;
//            if (seatcompare.getWidth() != seatIcon.getWidth()) return false;
//
//            for (int y = 0; y < seatcompare.getHeight(); ++y)
//                for (int x = 0; x < seatcompare.getWidth(); ++x)
//                    if (seatcompare.getPixel(x, y) != seatIcon.getPixel(x, y)) return false;
//
//            return true;
//        }
//    }

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


    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView seatIconn;
        TextView seatNo;

        public ViewHolder() {
            super(null);

        }

        public ViewHolder(final View itemView) {
            super(itemView);
            seatIconn = (ImageView) itemView.findViewById(R.id.seatIcon);
            seatNo = (TextView) itemView.findViewById(R.id.seatNo);

        }


    }


}