2017-06-10 114 views
-2

This is a application image如何拖放recyclerView元素?

我对Android Studio中的一个项目,我想拖和RecylerView掉落物品的图像在我的活动的容器...

在我的活动我有一个片段容器,这显示片段与一个RecyclerView和这个显示动物部分在JSON连接,它是可能的做一个拖放到图像移动到Cointainer使动物角色和发送数据到我的数据库,以及我怎么做?

+0

这看起来像是/不是问题。 –

+0

使用“ItemTouchHelper”检查此https://stackoverflow.com/questions/29901044/drag-and-drop-items-in-recyclerview-with-gridlayoutmanager –

回答

1

您必须实现ItemTouchHelper,这是如何做到这一点的例子:

1-添加您recyclerview

<android.support.v7.widget.RecyclerView 
     android:id="@+id/note_recycler_view" 
     android:scrollbars="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 

2 - 添加模型类

public class Customer { 
private Long id; 
private String name; 
private String emailAddress; 
private int imageId; 
private String imagePath; 
} 

3 - 添加依赖项

compile 'de.hdodenhof:circleimageview:2.0.0' 
compile 'com.squareup.picasso:picasso:2.5.2' 
compile 'com.yqritc:recyclerview-flexibledivider:1.2.6' 
compile 'com.google.code.gson:gson:2.3.1' 

4 - 添加Internet权限

<uses-permission android:name="android.permission.INTERNET" /> 

5-你活动创建的CustomerList并添加客户进去。

6-创建一个名为CustomerListAdapter类新

package com.okason.draganddrop; 

import android.content.Context; 
import android.graphics.Color; 
import android.support.v4.view.MotionEventCompat; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.okason.draganddrop.listeners.OnCustomerListChangedListener; 
import com.okason.draganddrop.listeners.OnStartDragListener; 
import com.okason.draganddrop.utilities.ItemTouchHelperAdapter; 
import com.okason.draganddrop.utilities.ItemTouchHelperViewHolder; 
import com.squareup.picasso.Picasso; 

import java.util.Collections; 
import java.util.List; 

/** 
* Created by Valentine on 10/18/2015. 
*/ 
public class CustomerListAdapter extends 
     RecyclerView.Adapter<CustomerListAdapter.ItemViewHolder> 
     implements ItemTouchHelperAdapter { 

private List<Customer> mCustomers; 
private Context mContext; 
private OnStartDragListener mDragStartListener; 
private OnCustomerListChangedListener mListChangedListener; 

public CustomerListAdapter(List<Customer> customers, Context context, 
          OnStartDragListener dragLlistener, 
          OnCustomerListChangedListener listChangedListener){ 
    mCustomers = customers; 
    mContext = context; 
    mDragStartListener = dragLlistener; 
    mListChangedListener = listChangedListener; 
} 


@Override 
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    View rowView = LayoutInflater.from 
    (parent.getContext()).inflate(R.layout.row_customer_list, parent, false); 
    ItemViewHolder viewHolder = new ItemViewHolder(rowView); 
    return viewHolder; 
} 

@Override 
public void onBindViewHolder(final ItemViewHolder holder, int position) { 

    final Customer selectedCustomer = mCustomers.get(position); 

    holder.customerName.setText(selectedCustomer.getName()); 
    holder.customerEmail.setText(selectedCustomer.getEmailAddress()); 
    Picasso.with(mContext) 
      .load(selectedCustomer.getImagePath()) 
      .placeholder(R.drawable.profile_icon) 
      .into(holder.profileImage); 



    holder.handleView.setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) { 
       mDragStartListener.onStartDrag(holder); 
      } 
      return false; 
     } 
    }); 
} 

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

@Override 
public void onItemMove(int fromPosition, int toPosition) { 
    Collections.swap(mCustomers, fromPosition, toPosition); 
    mListChangedListener.onNoteListChanged(mCustomers); 
    notifyItemMoved(fromPosition, toPosition); 
} 

@Override 
public void onItemDismiss(int position) { 

} 

public static class ItemViewHolder extends RecyclerView.ViewHolder implements 
     ItemTouchHelperViewHolder { 
    public final TextView customerName, customerEmail; 
    public final ImageView handleView, profileImage; 


    public ItemViewHolder(View itemView) { 
     super(itemView); 
     customerName = (TextView)itemView.findViewById(R.id.text_view_customer_name); 
     customerEmail = (TextView)itemView.findViewById(R.id.text_view_customer_email); 
     handleView = (ImageView)itemView.findViewById(R.id.handle); 
     profileImage = (ImageView)itemView.findViewById(R.id.image_view_customer_head_shot); 
    } 

    @Override 
    public void onItemSelected() { 
     itemView.setBahttp://valokafor.com/wp-admin/post.php?post=1804&action=edit#ckgroundColor(Color.LTGRAY); 
    } 

    @Override 
    public void onItemClear() { 
     itemView.setBackgroundColor(0); 
    } 
} 
} 

7-实施ItemTouchHelper 在你的应用程序包,添加ItemTouchHelperAdapter.java及以下内容:

public interface ItemTouchHelperAdapter { 
/** 
* Called when an item has been dragged far enough to trigger a move. This is called every time 
* an item is shifted, and not at the end of a "drop" event. 
* 
* @param fromPosition The start position of the moved item. 
* @param toPosition Then end position of the moved item. 

*/ 
void onItemMove(int fromPosition, int toPosition); 


/** 
* Called when an item has been dismissed by a swipe. 
* 
* @param position The position of the item dismissed. 

*/ 
void onItemDismiss(int position); 
} 

而在你的事业包,添加ItemTouchHelperViewHolder.java,下面是内容:

public interface ItemTouchHelperViewHolder { 
    /** 
     * Implementations should update the item view to indicate it's active state. 
    */ 
    void onItemSelected(); 


    /** 
    * state should be cleared. 
    */ 
    void onItemClear(); 
} 

在你的应用程序包,添加SimpleItemTouchHelperCallback.java这里是内容:

public class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback { 

private final ItemTouchHelperAdapter mAdapter; 

public SimpleItemTouchHelperCallback(ItemTouchHelperAdapter adapter) { 
    mAdapter = adapter; 
} 

@Override 
public boolean isLongPressDragEnabled() { 
    return true; 
} 

@Override 
public boolean isItemViewSwipeEnabled() { 
    return false; 
} 

@Override 
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { 
    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; 
    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; 
    return makeMovementFlags(dragFlags, swipeFlags); 
} 

@Override 
public boolean onMove(RecyclerView recyclerView, 
RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) { 
    mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition()); 
    return true; 
} 

@Override 
public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) { 
    mAdapter.onItemDismiss(viewHolder.getAdapterPosition()); 
} 

@Override 
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { 
    if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) { 
     ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder; 
     itemViewHolder.onItemSelected(); 
    } 

    super.onSelectedChanged(viewHolder, actionState); 
} 

@Override 
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { 
    super.clearView(recyclerView, viewHolder); 

    ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder; 
    itemViewHolder.onItemClear(); 
} 
} 

添加了一个叫做监听器,并添加一个名为OnStartDragListener.java这里的界面内容:

public interface OnCustomerListChangedListener { 
void onNoteListChanged(List<Customer> customers); 
} 

工具自定义行

private RecyclerView mRecyclerView; 
private CustomerListAdapter mAdapter; 
private RecyclerView.LayoutManager mLayoutManager; 
private ItemTouchHelper mItemTouchHelper; 
private List<Customer> mCustomers; 

在onCreate方法之后,添加此方法。然后可能在调用ToolBar之后,从onCreate()方法调用此方法。忽略一分钟的错误警告。

private void setupRecyclerView(){ 
     mRecyclerView = (RecyclerView) `findViewById(R.id.note_recycler_view);` 
     mRecyclerView.setHasFixedSize(true); 
     mLayoutManager = new LinearLayoutManager(this); 
     mRecyclerView.setLayoutManager(mLayoutManager); 
     mCustomers = SampleData.addSampleCustomers(); 

     //setup the adapter with empty list 
     mAdapter = new CustomerListAdapter(mCustomers, this, this, this); 
     ItemTouchHelper.Callback callback = new `SimpleItemTouchHelperCallback(mAdapter);` 
     mItemTouchHelper = new ItemTouchHelper(callback); 
     mItemTouchHelper.attachToRecyclerView(mRecyclerView); 
mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this) 

       .colorResId(R.color.colorPrimaryDark) 
       .size(2) 
       .build()); 
     mRecyclerView.setAdapter(mAdapter); 
    } 

更新您的MainActivity的签名以实现我们添加像下面的两个监听器,并使用Android工作室速战速决实现的方法。

public class MainActivity extends AppCompatActivity 
implements OnCustomerListChangedListener, 
    OnStartDragListener{ 

这里是方法之一的实施,我们将实现在下一节中的另一个。

@Override 
public void onStartDrag(RecyclerView.ViewHolder viewHolder) { 
    mItemTouchHelper.startDrag(viewHolder); 

} 

此时,您的拖放列表应该可以工作,我们现在要记住列表项在重新组织后的位置。就像我在文章开头提到的那样,这是通过将列表项的ID保存到SharedPreference来完成的,因此请继续并将以下类成员添加到文件的顶部。

private SharedPreferences mSharedPreferences; 
private SharedPreferences.Editor mEditor; 
public static final String LIST_OF_SORTED_DATA_ID = "json_list_sorted_data_id"; 
public final static String PREFERENCE_FILE = "preference_file"; 

而且在OnCreate()实例化SharedPreference像这样:

mSharedPreferences = this.getApplicationContext() 
      .getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE); 
    mEditor = mSharedPreferences.edit(); 

然后继续前进,实现侦听名单发生变化时,这里是该方法的实现另一种方法:

@Override 
public void onNoteListChanged(List<Customer> customers) { 
    //after drag and drop operation, the new list of Customers is passed in here 

    //create a List of Long to hold the Ids of the 
    //Customers in the List 
    List<Long> listOfSortedCustomerId = new ArrayList<Long>(); 

    for (Customer customer: customers){ 
     listOfSortedCustomerId.add(customer.getId()); 
    } 

    //convert the List of Longs to a JSON string 
    Gson gson = new Gson(); 
    String jsonListOfSortedCustomerIds = gson.toJson(listOfSortedCustomerId); 


    //save to SharedPreference 
    mEditor.putString(LIST_OF_SORTED_DATA_ID, jsonListOfSortedCustomerIds).commit(); 
    mEditor.commit(); 
} 

然后,此方法添加到您的MainActivity.java:

private List<Customer> getSampleData(){ 

    //Get the sample data 
    List<Customer> customerList = SampleData.addSampleCustomers(); 

    //create an empty array to hold the list of sorted Customers 
    List<Customer> sortedCustomers = new ArrayList<Customer>(); 

    //get the JSON array of the ordered of sorted customers 
    String jsonListOfSortedCustomerId = mSharedPreferences.getString(LIST_OF_SORTED_DATA_ID, ""); 

    //check for null 
    if (!jsonListOfSortedCustomerId.isEmpty()){ 

     //convert JSON array into a List<Long> 
     Gson gson = new Gson(); 
     List<Long> listOfSortedCustomersId = gson.fromJson 
     (jsonListOfSortedCustomerId, new TypeToken<List<Long>>(){}.getType()); 

     //build sorted list 
     if (listOfSortedCustomersId != null && listOfSortedCustomersId.size() > 0){ 
      for (Long id: listOfSortedCustomersId){ 
       for (Customer customer: customerList){ 
        if (customer.getId().equals(id)){ 
         sortedCustomers.add(customer); 
         customerList.remove(customer); 
         break; 
        } 
       } 
      } 
     } 

     //if there are still customers that were not in the sorted list 
     //maybe they were added after the last drag and drop 
     //add them to the sorted list 
     if (customerList.size() > 0){ 
      sortedCustomers.addAll(customerList); 
     } 

     return sortedCustomers; 
    }else { 
     return customerList; 
    } 
} 

现在更新setupRecyclerView()您从得到的数据线:

mCustomers = SampleData.addSampleCustomers(); 

到:

mCustomers = getSampleData(); 

Here is the source of my answer你可以找到关于每一个步骤的详细信息和说明。

+1

这是一个边界[链接专用答案](/ /元。 stackexchange.com/q/8231)。你应该扩大你的答案,在这里包含尽可能多的信息,并使用链接仅供参考。 – FrankerZ

+0

好的,谢谢,我会编辑它。 – Glory