我正在尝试将一些 iOS 功能移植到 Android。
我打算创建一个表格,向左滑动会显示 2 个按钮:编辑和删除。
我一直在玩它,我知道我非常接近。秘诀在于方法 OnChildDraw。
我想绘制一个适合文本删除的矩形,然后使用它们各自的背景颜色在其旁边绘制编辑文本。单击时剩余的空白应将该行恢复到其初始位置。
我已经设法在用户向两侧滑动时绘制背景,但我不知道如何添加监听器,一旦滑动到一侧,拖动功能就会开始出现异常。
我正在研究 Xamarin,但也接受纯 Java 解决方案,因为我可以轻松地将它们移植到 c#。
public class SavedPlacesItemTouchHelper : ItemTouchHelper.SimpleCallback
{
private SavedPlacesRecyclerviewAdapter adapter;
private Paint paint = new Paint();
private Context context;
public SavedPlacesItemTouchHelper(Context context, SavedPlacesRecyclerviewAdapter adapter) : base(ItemTouchHelper.ActionStateIdle, ItemTouchHelper.Left)
{
this.context = context;
this.adapter = adapter;
}
public override bool OnMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target)
{
return false;
}
public override void OnSwiped(RecyclerView.ViewHolder viewHolder, int direction)
{
}
public override void OnChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, bool isCurrentlyActive)
{
float translationX = dX;
View itemView = viewHolder.ItemView;
float height = (float)itemView.Bottom - (float)itemView.Top;
if (actionState == ItemTouchHelper.ActionStateSwipe && dX <= 0) // Swiping Left
{
translationX = -Math.Min(-dX, height * 2);
paint.Color = Color.Red;
RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
c.DrawRect(background, paint);
//viewHolder.ItemView.TranslationX = translationX;
}
else if (actionState == ItemTouchHelper.ActionStateSwipe && dX > 0) // Swiping Right
{
translationX = Math.Min(dX, height * 2);
paint.Color = Color.Red;
RectF background = new RectF((float)itemView.Right + translationX, (float)itemView.Top, (float)itemView.Right, (float)itemView.Bottom);
c.DrawRect(background, paint);
}
base.OnChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
}
}
}
这是我目前拥有的。
如果您知道如何添加听众或有任何建议,请发表评论!
更新:
我刚刚意识到双击该行的白色剩余空间已经将该行恢复到其初始状态。虽然不是一个水龙头:(
最佳答案
我遇到了同样的问题,并试图在网上找到解决方案。大多数解决方案使用两层方法(一层 View 项,另一层按钮),但我只想坚持使用 ItemTouchHelper。最后,我想出了一个可行的解决方案。请在下方查看。
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public abstract class SwipeHelper extends ItemTouchHelper.SimpleCallback {
public static final int BUTTON_WIDTH = YOUR_WIDTH_IN_PIXEL_PER_BUTTON
private RecyclerView recyclerView;
private List<UnderlayButton> buttons;
private GestureDetector gestureDetector;
private int swipedPos = -1;
private float swipeThreshold = 0.5f;
private Map<Integer, List<UnderlayButton>> buttonsBuffer;
private Queue<Integer> recoverQueue;
private GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
for (UnderlayButton button : buttons){
if(button.onClick(e.getX(), e.getY()))
break;
}
return true;
}
};
private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent e) {
if (swipedPos < 0) return false;
Point point = new Point((int) e.getRawX(), (int) e.getRawY());
RecyclerView.ViewHolder swipedViewHolder = recyclerView.findViewHolderForAdapterPosition(swipedPos);
View swipedItem = swipedViewHolder.itemView;
Rect rect = new Rect();
swipedItem.getGlobalVisibleRect(rect);
if (e.getAction() == MotionEvent.ACTION_DOWN || e.getAction() == MotionEvent.ACTION_UP ||e.getAction() == MotionEvent.ACTION_MOVE) {
if (rect.top < point.y && rect.bottom > point.y)
gestureDetector.onTouchEvent(e);
else {
recoverQueue.add(swipedPos);
swipedPos = -1;
recoverSwipedItem();
}
}
return false;
}
};
public SwipeHelper(Context context, RecyclerView recyclerView) {
super(0, ItemTouchHelper.LEFT);
this.recyclerView = recyclerView;
this.buttons = new ArrayList<>();
this.gestureDetector = new GestureDetector(context, gestureListener);
this.recyclerView.setOnTouchListener(onTouchListener);
buttonsBuffer = new HashMap<>();
recoverQueue = new LinkedList<Integer>(){
@Override
public boolean add(Integer o) {
if (contains(o))
return false;
else
return super.add(o);
}
};
attachSwipe();
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int pos = viewHolder.getAdapterPosition();
if (swipedPos != pos)
recoverQueue.add(swipedPos);
swipedPos = pos;
if (buttonsBuffer.containsKey(swipedPos))
buttons = buttonsBuffer.get(swipedPos);
else
buttons.clear();
buttonsBuffer.clear();
swipeThreshold = 0.5f * buttons.size() * BUTTON_WIDTH;
recoverSwipedItem();
}
@Override
public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
return swipeThreshold;
}
@Override
public float getSwipeEscapeVelocity(float defaultValue) {
return 0.1f * defaultValue;
}
@Override
public float getSwipeVelocityThreshold(float defaultValue) {
return 5.0f * defaultValue;
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
int pos = viewHolder.getAdapterPosition();
float translationX = dX;
View itemView = viewHolder.itemView;
if (pos < 0){
swipedPos = pos;
return;
}
if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
if(dX < 0) {
List<UnderlayButton> buffer = new ArrayList<>();
if (!buttonsBuffer.containsKey(pos)){
instantiateUnderlayButton(viewHolder, buffer);
buttonsBuffer.put(pos, buffer);
}
else {
buffer = buttonsBuffer.get(pos);
}
translationX = dX * buffer.size() * BUTTON_WIDTH / itemView.getWidth();
drawButtons(c, itemView, buffer, pos, translationX);
}
}
super.onChildDraw(c, recyclerView, viewHolder, translationX, dY, actionState, isCurrentlyActive);
}
private synchronized void recoverSwipedItem(){
while (!recoverQueue.isEmpty()){
int pos = recoverQueue.poll();
if (pos > -1) {
recyclerView.getAdapter().notifyItemChanged(pos);
}
}
}
private void drawButtons(Canvas c, View itemView, List<UnderlayButton> buffer, int pos, float dX){
float right = itemView.getRight();
float dButtonWidth = (-1) * dX / buffer.size();
for (UnderlayButton button : buffer) {
float left = right - dButtonWidth;
button.onDraw(
c,
new RectF(
left,
itemView.getTop(),
right,
itemView.getBottom()
),
pos
);
right = left;
}
}
public void attachSwipe(){
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(this);
itemTouchHelper.attachToRecyclerView(recyclerView);
}
public abstract void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons);
public static class UnderlayButton {
private String text;
private int imageResId;
private int color;
private int pos;
private RectF clickRegion;
private UnderlayButtonClickListener clickListener;
public UnderlayButton(String text, int imageResId, int color, UnderlayButtonClickListener clickListener) {
this.text = text;
this.imageResId = imageResId;
this.color = color;
this.clickListener = clickListener;
}
public boolean onClick(float x, float y){
if (clickRegion != null && clickRegion.contains(x, y)){
clickListener.onClick(pos);
return true;
}
return false;
}
public void onDraw(Canvas c, RectF rect, int pos){
Paint p = new Paint();
// Draw background
p.setColor(color);
c.drawRect(rect, p);
// Draw Text
p.setColor(Color.WHITE);
p.setTextSize(LayoutHelper.getPx(MyApplication.getAppContext(), 12));
Rect r = new Rect();
float cHeight = rect.height();
float cWidth = rect.width();
p.setTextAlign(Paint.Align.LEFT);
p.getTextBounds(text, 0, text.length(), r);
float x = cWidth / 2f - r.width() / 2f - r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
c.drawText(text, rect.left + x, rect.top + y, p);
clickRegion = rect;
this.pos = pos;
}
}
public interface UnderlayButtonClickListener {
void onClick(int pos);
}
}
用法:
SwipeHelper swipeHelper = new SwipeHelper(this, recyclerView) {
@Override
public void instantiateUnderlayButton(RecyclerView.ViewHolder viewHolder, List<UnderlayButton> underlayButtons) {
underlayButtons.add(new SwipeHelper.UnderlayButton(
"Delete",
0,
Color.parseColor("#FF3C30"),
new SwipeHelper.UnderlayButtonClickListener() {
@Override
public void onClick(int pos) {
// TODO: onDelete
}
}
));
underlayButtons.add(new SwipeHelper.UnderlayButton(
"Transfer",
0,
Color.parseColor("#FF9502"),
new SwipeHelper.UnderlayButtonClickListener() {
@Override
public void onClick(int pos) {
// TODO: OnTransfer
}
}
));
underlayButtons.add(new SwipeHelper.UnderlayButton(
"Unshare",
0,
Color.parseColor("#C7C7CB"),
new SwipeHelper.UnderlayButtonClickListener() {
@Override
public void onClick(int pos) {
// TODO: OnUnshare
}
}
));
}
};
注意:这个帮助类是为左滑设计的。您可以在 SwipeHelper 的 构造函数中更改滑动方向,并在 onChildDraw 方法中根据 dX 进行相应的更改。
如果要在按钮中显示图片,只需在UnderlayButton中使用imageResId,并重新实现onDraw方法.
有一个已知的错误,当你从一个项目对角滑动一个项目到另一个项目时,第一个触摸的项目会闪烁一点。这可以通过减小 getSwipeVelocityThreshold 的值来解决,但这会使用户更难滑动项目。您还可以通过更改 getSwipeThreshold 和 getSwipeEscapeVelocity 中的另外两个值来调整滑动感觉。查看 ItemTouchHelper 源码,评论很有帮助。
我相信有很多地方可以优化。如果您想坚持使用 ItemTouchHelper,此解决方案只是给出了一个想法。如果您在使用它时遇到问题,请告诉我。下面是一个截图。
致谢:这个解决方案的灵感主要来自 AdamWei 在 post 中的回答
关于android - 滑动时的 RecyclerView ItemTouchHelper 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44965278/
最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路
已经有一个问题回答了如何将“America/Los_Angeles”转换为“PacificTime(US&Canada)”。但是我想将“美国/太平洋”和其他过时的时区转换为RailsTimeZone。我无法在图书馆中找到任何可以帮助我完成此任务的东西。 最佳答案 来自RailsActiveSupport::TimeZonedocs:TheversionofTZInfobundledwithActiveSupportonlyincludesthedefinitionsnecessarytosupportthezonesdefinedb
我希望用户从一个模型的三个选项中选择一个。即我有一个模型视频,可以被评为正面/负面/未知目前我有三列bool值(pos/neg/unknown)。这是处理这种情况的最佳方式吗?为此,表单应该是什么样的?目前我有类似的东西但显然它允许多项选择,而我试图将它限制为只有一个..怎么办? 最佳答案 如果要使用字符串列,让我们说rating。然后在你的表单中:#...#...它只允许一个选择编辑完全相同但使用radio_button_tag: 关于ruby-on-rails-Rails单选按钮-模
基本上,我试图在用户单击链接(或按钮或某种类型的交互元素)时执行Rails方法。我试着把它放在View中:但这似乎没有用。它最终只是在用户甚至没有点击“添加”链接的情况下调用该函数。我也用link_to试过了,但也没用。我开始认为没有一种干净的方法可以做到这一点。无论如何,感谢您的帮助。附言。我在ApplicationController中定义了该方法,它是一个辅助方法。 最佳答案 View和Controller是相互独立的。为了使链接在Controller内执行函数调用,您需要对应用程序中的端点执行ajax调用。该路由应调用rub
我在ruby表单中有一个提交按钮f.submitbtn_text,class:"btnbtn-onemgt12mgb12",id:"btn_id"我想在不使用任何javascript的情况下通过ruby禁用此按钮 最佳答案 添加disabled:true选项。f.submitbtn_text,class:"btnbtn-onemgt12mgb12",id:"btn_id",disabled:true 关于ruby-on-rails-如何在Rails中添加禁用的提交按钮,我们在St
我在事件管理员编辑页面中有嵌套资源,但我只想允许管理员编辑现有资源的内容,而不是添加新的嵌套资源。我的代码看起来像这样:formdo|f|f.inputsdof.input:authorf.input:contentf.has_many:commentsdo|comment_form|comment_form.input:contentcomment_form.input:_destroy,as::boolean,required:false,label:'Remove'endendf.actionsend但它在输入下添加了“添加新评论”按钮。我怎样才能禁用它,并只为主窗体保留f.ac
以下测试中的第3个失败:specify{(0.6*2).shouldeql(1.2)}specify{(0.3*3).shouldeql(0.3*3)}specify{(0.3*3).shouldeql(0.9)}#thisonefails这是为什么呢?这是浮点问题还是ruby或rspec问题? 最佳答案 从rspec-2.1开始specify{(0.6*2).shouldbe_within(0.01).of(1.2)}在那之前:specify{(0.6*2).shouldbe_close(1.2,0.01)}
正如标题所暗示的那样,我只是在寻找一种无需单击即可按下Shoes中的按钮的方法。我已经搜索了论坛,但不幸的是找不到任何东西。谢谢 最佳答案 这在Windows下的红色鞋子中不起作用,因为Windows控件窃取了所有事件。不过,我设法在window下穿着绿鞋工作。举个例子['green_shoes'].each(&method(:require))Shoes.app{e=edit_linebutton("Clickme!"){alert("Youclickedme.")}keypress{|k|alert("YoupressedEnt
我有这个代码:#encoding:utf-8require'nokogiri's="CaféVerona".encode('UTF-8')puts"Originalstring:#{s}"@doc=Nokogiri::HTML::DocumentFragment.parse(s)links=@doc.css('a')only_text='CaféVerona'.encode('UTF-8')puts"Replacementtext:#{only_text}"links.first.replace(only_text)puts@doc.to_html但是,输出是这样的:Originals
我正在尝试使用Mechanize来模拟点击网页上的按钮,然后会在浏览器中启动文件下载。这是我的代码片段form=page.forms.first#=>Mechanize::Formform=agent.page.form_with(:name=>"aspnetForm")button=form.button_with(:value=>"GPXfile")ppbuttonagent.submit(form,button)pp按钮的输出是这样显示的,这意味着它是右键:#但是在发出“agent.submit(form,button)”之后,我怎样才能让Mechanize检索单击该按钮时将发送