在拖动项目时,为什么在Advanced Recycler View中自动滚动不起作用?

时间:2018-01-13 09:40:59

标签: java android android-recyclerview android-scrollview

我正在创建一个Android应用程序。我正在使用先进的Recycler View。我实现了拖放功能。

当我拖动某个项目时,如果我超出屏幕尺寸,则该列表不会自动滚动。

也就是说,拖动的项目进入屏幕结束并消失。

由于这是第三方图书馆,我对此并不了解。

为什么拖动项目时列表不会自动滚动?

包含回收者视图的对话框:

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

    <RelativeLayout
        android:id="@+id/toolbar_elite"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp">

        <android.support.v7.widget.AppCompatImageView
            android:id="@+id/elite_list_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerVertical="true"
            android:background="@null"
            android:cropToPadding="true"
            android:paddingLeft="4dp"
            android:paddingRight="0dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/left_white" />

        <com.kyleduo.switchbutton.SwitchButton
            android:id="@+id/elite_list_switch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="10dp"
            android:textColor="@color/colorWhite"
            android:textSize="16sp"
            android:textStyle="bold"
            app:kswBackColor="@color/black"
            app:kswBackDrawable="@drawable/switch_bg"
            app:kswBackMeasureRatio="1.45"
            app:kswBackRadius="7.5sp"
            app:kswTextOff="@string/all_caps"
            app:kswThumbDrawable="@drawable/switch_background_white"
            app:kswThumbHeight="35dp"
            app:kswThumbMarginBottom="-20dp"
            app:kswThumbMarginLeft="4dp"
            app:kswThumbMarginRight="3dp"
            app:kswThumbMarginTop="-20dp"
            app:kswThumbRadius="20dp"
            app:kswThumbWidth="35dp" />

        <Button
            android:id="@+id/elite_remove"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="10dp"
            android:text="Remove"
            android:textAllCaps="false"
            android:textColor="@color/black"
            android:visibility="gone" />

    </RelativeLayout>

    <TextView
        android:id="@+id/elite_list_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/toolbar_elite"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/username_elite_7"
        android:textAllCaps="true"
        android:textColor="@android:color/black"
        android:textSize="28sp"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/elite_list_username"
        android:layout_marginTop="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/no_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:gravity="center"
                android:text="No List Found"
                android:textAllCaps="true"
                android:textColor="@android:color/black"
                android:textSize="18sp"
                android:textStyle="bold"
                android:visibility="gone" />


            <android.support.v7.widget.RecyclerView
                android:id="@+id/elite_drivers_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />


        </RelativeLayout>

    </ScrollView>

</RelativeLayout>

物品设计:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/background_line_view"
    android:padding="10dp"
    android:id="@+id/elite_recycle">

    <ImageView
        android:id="@+id/elite_driver_image"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@drawable/ic_nav_profile"
        android:foregroundGravity="center" />

    <ImageView
        android:id="@+id/background"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:background="@drawable/check_box_unchecked"
        android:scaleType="fitXY"
        android:layout_marginRight="25dp"
         android:foregroundGravity="center"
        android:layout_centerVertical="true"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="70dp" />

    <android.support.v7.widget.AppCompatCheckBox
        android:id="@+id/elite_check_box"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:background="@android:color/transparent"
        android:button="@android:color/transparent"
        android:layout_marginRight="30dp"
        android:layout_centerVertical="true"
        android:layout_alignStart="@+id/background" />

    <ImageView
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:scaleType="fitXY"
         android:layout_marginStart="20dp"
        android:layout_marginEnd="25dp"
        android:background="@drawable/remove"
        android:id="@+id/remove_img"
        android:layout_marginTop="3dp"
        android:foregroundGravity="left"
         android:layout_centerVertical="true"
        android:layout_alignParentEnd="true" />
    <TextView
        android:layout_width="55dp"
        android:layout_height="18dp"
        android:text="Remove"
        android:id="@+id/remove_tv"
        android:textColor="@color/black"
        android:textAllCaps="true"
        android:paddingTop="3dp"
        android:layout_marginEnd="5dp"
        android:layout_toStartOf="@+id/elite_check_box"
        android:layout_alignBottom="@+id/elite_driver_vehicle"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/elite_driver_vehicle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/elite_driver_image"
        android:layout_toRightOf="@id/elite_driver_image"
        android:layout_toLeftOf="@id/elite_check_box"
        android:paddingBottom="8dp"
        android:text="@string/vehicle_type"
        android:textAllCaps="true"
        android:textColor="@color/black"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/elite_driver_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/elite_driver_vehicle"
        android:layout_toRightOf="@id/elite_driver_image"
        android:layout_toLeftOf="@id/elite_check_box"
        android:paddingTop="5dp"
        android:text="@string/driver_name"
        android:textAllCaps="true"
        android:textColor="@color/black"
        android:textSize="18sp" />
    <View
        android:id="@+id/drag_handle2"
        android:layout_width="32dp"
        android:layout_height="match_parent" />


</RelativeLayout>

适配器类:

package com.nuvo.rider.adapter;


public class EliteDriverListAdapter extends RecyclerView.Adapter<EliteDriverListAdapter.ViewHolder>   implements DraggableItemAdapter<EliteDriverListAdapter.ViewHolder> {
    public List<String> strSelectedDrivers = new ArrayList<>();
    public boolean mIsAllClicked = false;
    private Activity activity;
    private List<YourTrips> AlertMessageList = new ArrayList<>();
    private List<YourTrips> eliteList;
    String riderId,driverId;
    ProgressDialog progressDialog;
   private interface Draggable extends DraggableItemConstants {
   }
    //  YourTrips driver;
    public EliteDriverListAdapter(Activity activity, List<YourTrips> eliteList) {
        this.activity = activity;
        this.eliteList = eliteList;


        SharedPreferences prefs = activity.getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
        riderId = prefs.getString("userid", null);
        System.out.println("UserID in driver_id" + riderId + driverId);
        setHasStableIds(true);

    }

    @Override
    public EliteDriverListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View listView = activity.getLayoutInflater().inflate(R.layout.elite_list_adapter, parent, false);
        FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font));
        fontChanger.replaceFonts((ViewGroup) listView);
        AlertMessageList = getFavorites(activity);
        return new ViewHolder(listView);

    }

    @Override
    public void onBindViewHolder(final EliteDriverListAdapter.ViewHolder holder, final int position) {
       boolean dragging = false;


        final int dragState = holder.getDragStateFlags();
        if (((dragState & Draggable.STATE_FLAG_IS_UPDATED) != 0)) {
            int bgResId=0;

            if ((dragState & Draggable.STATE_FLAG_IS_ACTIVE) != 0) {
                bgResId = Color.GRAY;
                dragging = true;
                if (position == 7 ) bgResId = Color.GREEN;
                ;

                // need to clear drawable state here to get correct appearance of the dragging item.
              // DrawableUtils.clearState(holder.lastview.getForeground());
            } else if ((dragState & Draggable.STATE_FLAG_DRAGGING) != 0) {
            //    bgResId = Color.GREEN;
            } else {
               // bgResId =Color.YELLOW;
            }

            holder.lastview.setBackgroundColor(bgResId);
            System.out.println("elite drag color = > "+bgResId );
        }

       final YourTrips driver = eliteList.get(position);
        if (mIsAllClicked) {
            System.out.println("if-->");
             Constants.strSelectedDrivers.add(driver.getDriverID());
            holder.elite_check_box.setChecked(true);
            holder.background.setImageResource(R.drawable.check_box_checked);
        } else {
            System.out.println("else if-->");
            holder.elite_check_box.setChecked(false);
            holder.background.setImageResource(R.drawable.check_box_unchecked);
        }

        if (driver.getDriverImage() != null && !driver.getDriverImage().isEmpty()) {
            Glide.with(activity).load(driver.getDriverImage()).asBitmap().centerCrop().error(R.drawable.account_picture)
                    .skipMemoryCache(false).into(new BitmapImageViewTarget(holder.profileImage) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(activity.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    holder.profileImage.setImageDrawable(circularBitmapDrawable);
                }
            });
        }

        if (driver.getDriverName() != null && !driver.getDriverName().isEmpty()) {
            holder.elite_driver_name.setText(driver.getDriverName());
        System.out.println("Elite == > driver name"+driver.getDriverName());
        }

        if (driver.getCarType() != null && !driver.getCarType().isEmpty()) {
            holder.elite_driver_vehicle.setText(driver.getCarType().replaceAll("_"," ").replaceAll("[\\[\\]]", "").trim());
            System.out.println("Elite == > driver cartype"+driver.getCarType());

        }
        if (position == 7 && dragging == false) holder.lastview.setBackgroundColor(Color.GREEN);
        else if (position < 7 && dragging == false) holder.lastview.setBackgroundColor (activity.getResources().getColor(R.color.colorPrimary));

        holder.elite_check_box.setTag(position);
        if (!mIsAllClicked) {
            if (driver.getCheckedState() != null && !driver.getCheckedState().isEmpty()) {
                System.out.println("checked status in the adapter-" + driver.getCheckedState());
                if (driver.getCheckedState().equals("checked")) {
                    holder.elite_check_box.setChecked(true);
                    holder.background.setImageResource(R.drawable.check_box_checked);

                    System.out.println("if part");
                } else if (driver.getCheckedState().equals("unchecked")) {
                    System.out.println("else part");
                    holder.elite_check_box.setChecked(false);
                    holder.background.setImageResource(R.drawable.check_box_unchecked);

                }
            }
        }



        holder.elite_check_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String driverId = eliteList.get((Integer) buttonView.getTag()).getDriverID();
                if (!mIsAllClicked) {
                    if (isChecked) {
                        Log.d("adapter", String.valueOf((Integer) buttonView.getTag()));
                        holder.background.setImageResource(R.drawable.check_box_checked);
                        if (driverId != null && !driverId.isEmpty())
                            Constants.strSelectedDrivers.add(driverId);
                        for(int i =0;i<Constants.strSelectedDrivers.size();i++){
                            System.out.println("elite driver added selected id"+Constants.strSelectedDrivers.get(i));
                        }
                      } else {
                        System.out.println("clear id in the checkbox");
                        holder.background.setImageResource(R.drawable.check_box_unchecked);
                        if (driverId != null && !driverId.isEmpty() && Constants.strSelectedDrivers.contains(driverId)) {
                            Constants.strSelectedDrivers.remove(driverId);
                        }
                    }

                    System.out.println("THE ADAPTER SELECTEDDRIVERS"+Constants.strSelectedDrivers);
                }
            }
        });
        holder.elite_driver_remove.setTag(position);


        holder.elite_driver_remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                driverId = driver.getDriverID();
                AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);

                String title = GlobalAlertMessage("elite_driver_remove_r","Alert!","Are you sure ! You Wanna Remove this Elite Driver "+driver.getDriverName()+" from Your Elite List ?")[0];
                String desc = GlobalAlertMessage("elite_driver_remove_r","Alert!","Are you sure ! You Wanna Remove this Elite Driver "+driver.getDriverName()+" from Your Elite List ?")[1];

                builder.setTitle(title);
                builder.setMessage(desc);

                builder.setCancelable(true);
                builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        System.out.println("remove driver id-->"+driver.getDriverID()+" "+riderId);
                        String url = Constants.LIVE_URL + "removeEliteDriver/rider_id/" + riderId + "/driver_id/" + driver.getDriverID();
                        System.out.println("Elite remove URL : "+url);
                        showDialog();
                        JsonArrayRequest remove_elite = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                try {
                                    JSONObject response2 = response.getJSONObject(0);
                                    if (response2.optString("status").equalsIgnoreCase("success")){

                                       dismissDialog();
                                        Toast.makeText(activity, "This driver "+driver.getDriverName()+" is successfully removed from your elite driver list.",
                                                Toast.LENGTH_SHORT).show();
                                        eliteList.remove(position);
                                        EliteDriverListAdapter.this.notifyItemRemoved(position);
                                        EliteDriverListAdapter.this.notifyDataSetChanged();


                                    }
                                    else
                                    {
                                        dismissDialog();
                                        Toast.makeText(activity, "This driver "+driver.getDriverName()+" is NOT removed from your elite driver list.",
                                                Toast.LENGTH_SHORT).show();
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    dismissDialog();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                System.out.println("get error response"+error.getMessage());
                                Toast.makeText(activity,"Internet Connection error!",Toast.LENGTH_LONG).show();
                            }
                        });
                        remove_elite.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                        AppController.getInstance().addToRequestQueue(remove_elite);

                    }
                });

                builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        holder.elite_driver_remove.setSelected(false);
                        dialogInterface.dismiss();

                    }
                });
                builder.show();
            }

        });

    }

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

    @Override
    public boolean onCheckCanStartDrag(ViewHolder holder, int position, int x, int y) {


 return true;
    }

    @Override
    public ItemDraggableRange onGetItemDraggableRange(ViewHolder holder, int position) {

        return null;
    }

    @Override
    public void onMoveItem(final int fromPosition, final int toPosition) {
       YourTrips removed = eliteList.remove(fromPosition);
                                    eliteList.add(toPosition, removed);
                                    notifyDataSetChanged();

                                    dismissDialog();

                                    Toast.makeText(activity, "Elite Driver positions changed",
                                            Toast.LENGTH_SHORT).show();

    }

    @Override
    public boolean onCheckCanDrop(int draggingPosition, int dropPosition) {
        return false;
    }


    @Override
    public long getItemId(int position) {
        // requires static value, it means need to keep the same value
        // even if the item position has been changed.
        return eliteList.get(position).getId();
    }

    class ViewHolder extends AbstractDraggableItemViewHolder {
        ImageView profileImage, background, elite_driver_remove;
        CheckBox elite_check_box;
        TextView elite_driver_name, elite_driver_vehicle, elite_remove;
        RelativeLayout lastview;
        View dragHandle;

        ViewHolder(View itemView) {
            super(itemView);
            elite_driver_vehicle = (TextView) itemView.findViewById(R.id.elite_driver_vehicle);
            elite_driver_name = (TextView) itemView.findViewById(R.id.elite_driver_name);
            elite_check_box = (CheckBox) itemView.findViewById(R.id.elite_check_box);
            profileImage = (ImageView) itemView.findViewById(R.id.elite_driver_image);
            background = (ImageView) itemView.findViewById(R.id.background);
            elite_driver_remove = (ImageView) itemView.findViewById(R.id.remove_img);
            elite_remove = (TextView) itemView.findViewById(R.id.remove_tv);
            dragHandle = (View) itemView.findViewById(R.id.drag_handle2);
            lastview = (RelativeLayout) itemView.findViewById(R.id.elite_recycle);

        }
    }
    public String[] GlobalAlertMessage(String code,String title,String desc){
        String[] arr = new String[2];

        for (int i1 = 0; i1 < AlertMessageList.size(); i1++) {
            if (AlertMessageList.get(i1).getmessageCode().equals(code)) {
                arr[0] = AlertMessageList.get(i1).getMessagetitle();
                arr[1]=  AlertMessageList.get(i1).getmessageDesc();
                System.out.println("title--->"+title);
                System.out.println("desc--->"+desc);
                break;
            } else {
                System.out.println("Not Exist : " + AlertMessageList.get(i1));
                arr[0] = title;
                arr[1] = desc;
            }
        }
        return arr;

    }



    public ArrayList<YourTrips> getFavorites(Context context) {
        SharedPreferences settings;
        List<YourTrips> favorites;

        settings = context.getSharedPreferences(Constants.MY_PREFS_NAME_ALERT,
                Context.MODE_PRIVATE);

        if (settings.contains(Constants.FAVORITES)) {
            String jsonFavorites = settings.getString(Constants.FAVORITES, null);
            Gson gson = new Gson();
            YourTrips[] favoriteItems = gson.fromJson(jsonFavorites,
                    YourTrips[].class);

            favorites = Arrays.asList(favoriteItems);
            favorites = new ArrayList<YourTrips>(favorites);
        } else
            return null;

        return (ArrayList<YourTrips>) favorites;
    }


}

启动Dialog的活动

    final Dialog eliteDriverList = new Dialog(RideLater.this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
    eliteDriverList.setContentView(R.layout.dialog_elite_drivers_list);
    eliteDriverList.setCancelable(true);
    ImageView elite_list_back = (ImageView) eliteDriverList.findViewById(R.id.elite_list_back);
    SwitchButton elite_list_switch = (SwitchButton) eliteDriverList.findViewById(R.id.elite_list_switch);
    TextView elite_list_username = (TextView) eliteDriverList.findViewById(R.id.elite_list_username);
    Button eliteSubmit = (Button)   eliteDriverList.findViewById (R.id.submit_elite);
    RecyclerView elite_drivers_list = (RecyclerView) eliteDriverList.findViewById(R.id.elite_drivers_list);
    RecyclerViewDragDropManager dragMgr = new RecyclerViewDragDropManager();
    RelativeLayout last_view = (RelativeLayout) eliteDriverList.findViewById(R.id.last_view);

    dragMgr.setInitiateOnLongPress(true);
    dragMgr.setInitiateOnMove(false);

    elite_list_switch.setTypeface(normal);
    elite_list_username.setTypeface(demibold);

    elite_list_username.setText(getString(R.string.username_elite_7, riderfirstname));

    final EliteDriverListAdapter eliteDriverAdapter = new EliteDriverListAdapter(RideLater.this, listFeedItems);
    RecyclerView.Adapter wrappedAdapter = dragMgr.createWrappedAdapter(eliteDriverAdapter);

    elite_drivers_list.setLayoutManager(new LinearLayoutManager(RideLater.this, LinearLayoutManager.VERTICAL, false));
    elite_drivers_list.setNestedScrollingEnabled(true);
    elite_drivers_list.setAdapter(wrappedAdapter);
    ((SimpleItemAnimator) elite_drivers_list.getItemAnimator()).setSupportsChangeAnimations(false);
    dragMgr.attachRecyclerView(elite_drivers_list);

    getEliteFromWeb(eliteDriverAdapter,last_view);

    elite_list_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                eliteDriverAdapter.strSelectedDrivers.clear();
                eliteDriverAdapter.mIsAllClicked = true;
                eliteDriverAdapter.notifyDataSetChanged();
            } else {
                eliteDriverAdapter.strSelectedDrivers.clear();
                eliteDriverAdapter.mIsAllClicked = false;
                eliteDriverAdapter.notifyDataSetChanged();
            }
        }
    });

    elite_list_back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isFinishing()) {
                listFeedItems.clear();
                eliteDriverAdapter.notifyDataSetChanged();
            }
            eliteDriverList.dismiss();
        }
    });

    eliteSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isFinishing()) {
                listFeedItems.clear();
                eliteDriverAdapter.notifyDataSetChanged();
            }
            eliteDriverList.dismiss();
        }
    });

    if (!isFinishing()) {

        eliteDriverList.show();
    }
}

0 个答案:

没有答案