简短版:
DragEvent?有 How to register a DragEvent while already inside one and have it listen in the current DragEvent? ,但我真的想要一个更清洁的解决方案。
建议的 GONE->VISIBLE 解决方法要“正确”是相当复杂的,因为您需要确保仅在列表项变得可见时才使用它,而不是无条件地在所有当前 ListView 项上使用它。在此 hack 略有漏洞,没有更多的解决方法代码来使其正确。
长版:
我有一个 ListView。 ListView 的元素是包含可拖动符号(小框)的自定义 View ,例如类似这样:
可以在 ListView 的项目之间拖动小框,就像将元素排序到框中一样。列表项上的拖动处理程序或多或少是微不足道的:
@Override
public boolean onDragEvent(DragEvent event)
{
if ((event.getLocalState() instanceof DragableSymbolView)) {
final DragableSymbolView draggedView = (DragableSymbolView) event.getLocalState();
if (draggedView.getTag() instanceof SymbolData) {
final SymbolData symbol = (SymbolData) draggedView.getTag();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
return true;
case DragEvent.ACTION_DRAG_ENTERED:
setSelected(true);
return true;
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DRAG_EXITED:
setSelected(false);
return true;
case DragEvent.ACTION_DROP:
setSelected(false);
// [...] remove symbol from soruce box and add to current box
requestFocus();
break;
}
}
}
return super.onDragEvent(event);
}
将指针悬停在符号上并开始拖动(即将其移动到一个小阈值之外)时,拖动开始。
但是,现在屏幕尺寸可能不足以包含所有框,因此 ListView 需要滚动。我发现我需要自己实现滚动的困难方法,因为 ListView 在拖动时不会自动滚动。
进来ListViewScrollingDragListener:
public class ListViewScrollingDragListener
implements View.OnDragListener {
private final ListView _listView;
public static final int DEFAULT_SCROLL_BUFFER_DIP = 96;
public static final int DEFAULT_SCROLL_DELTA_UP_DIP = 48;
public static final int DEFAULT_SCROLL_DELTA_DOWN_DIP = 48;
private int _scrollDeltaUp;
private int _scrollDeltaDown;
private boolean _doScroll = false;
private boolean _scrollActive = false;
private int _scrollDelta = 0;
private int _scrollDelay = 250;
private int _scrollInterval = 100;
private int _scrollBuffer;
private final Rect _visibleRect = new Rect();
private final Runnable _scrollHandler = new Runnable() {
@Override
public void run()
{
if (_doScroll && (_scrollDelta != 0) && _listView.canScrollVertically(_scrollDelta)) {
_scrollActive = true;
_listView.smoothScrollBy(_scrollDelta, _scrollInterval);
_listView.postDelayed(this, _scrollInterval);
} else {
_scrollActive = false;
}
}
};
public ListViewScrollingDragListener(final ListView listView, final boolean attach)
{
_scrollBuffer = UnitUtil.dipToPixels(listView, DEFAULT_SCROLL_BUFFER_DIP);
_scrollDeltaUp = -UnitUtil.dipToPixels(listView, DEFAULT_SCROLL_DELTA_UP_DIP);
_scrollDeltaDown = UnitUtil.dipToPixels(listView, DEFAULT_SCROLL_DELTA_DOWN_DIP);
_listView = listView;
if (attach) {
_listView.setOnDragListener(this);
}
}
public ListViewScrollingDragListener(final ListView listView)
{
this(listView, true);
}
protected void handleDragLocation(final float x, final float y)
{
_listView.getGlobalVisibleRect(_visibleRect);
if (_visibleRect.contains((int) x, (int) y)) {
if (y < _visibleRect.top + _scrollBuffer) {
_scrollDelta = _scrollDeltaUp;
_doScroll = true;
} else if (y > _visibleRect.bottom - _scrollBuffer) {
_scrollDelta = _scrollDeltaDown;
_doScroll = true;
} else {
_doScroll = false;
_scrollDelta = 0;
}
if ((_doScroll) && (!_scrollActive)) {
_scrollActive = true;
_listView.postDelayed(_scrollHandler, _scrollDelay);
}
}
}
public ListView getListView()
{
return _listView;
}
@Override
public boolean onDrag(View v, DragEvent event)
{
/* hide sequence controls during drag */
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_ENTERED:
_doScroll = true;
break;
case DragEvent.ACTION_DRAG_EXITED:
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DROP:
_doScroll = false;
break;
case DragEvent.ACTION_DRAG_LOCATION:
handleDragLocation(event.getX(), event.getY());
break;
}
return true;
}
}
当您在其可见区域的上边界或下边界附近拖动时,这基本上会滚动 ListView。它并不完美,但已经足够好了。
但是,有一个问题:
当列表滚动到之前不可见的元素时,该元素不会接收到 DragEvent。在其上拖动符号时,它不会被选中(突出显示),也不接受掉落。
关于如何使“卷入” View 从已经激活的拖放操作接收 DragEvent 有什么想法吗?
最佳答案
所以根本问题是 ViewGroup(即 ListView 扩展)缓存了一个子级列表以通知 DragEvent。此外,它仅在接收到 ACTION_DRAG_STARTED 时填充此缓存。有关更多详细信息,请阅读源代码 here .
关于解决方案!我们不是在 ListView 的各个行上监听放置事件,而是在 ListView 本身上监听它们。然后,根据事件的坐标,我们将找出被拖动的 View 从哪一行拖动到哪一行或悬停在哪一行。当删除发生时,我们将执行从前一行中删除并添加到新行的事务。
private void init(Context context) {
setAdapter(new RandomIconAdapter()); // Adapter that contains our data set
setOnDragListener(new ListDragListener());
mListViewScrollingDragListener = new ListViewScrollingDragListener(this, false);
}
ListViewScrollingDragListener mListViewScrollingDragListener;
private class ListDragListener implements OnDragListener {
// The view that our dragged view would be dropped on
private View mCurrentDropZoneView = null;
private int mDropStartRowIndex = -1;
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_LOCATION:
// Update the active drop zone based on the position of the event
updateCurrentDropZoneView(event);
// Funnel drag events to separate listener to handle scrolling near edges
mListViewScrollingDragListener.onDrag(v, event);
if( mDropStartRowIndex == -1 ) // Only initialize once per drag->drop gesture
{
mDropStartRowIndex = indexOfChild(mCurrentDropZoneView) + getFirstVisiblePosition();
log("mDropStartRowIndex %d", mDropStartRowIndex);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DRAG_EXITED:
mCurrentDropZoneView = null;
mDropStartRowIndex = -1;
break;
case DragEvent.ACTION_DROP:
// Update our data set based on the row that the dragged view was dropped in
int finalDropRow = indexOfChild(mCurrentDropZoneView) + getFirstVisiblePosition();
updateDataSetWithDrop(mDropStartRowIndex, finalDropRow);
// Let adapter update ui
((BaseAdapter)getAdapter()).notifyDataSetChanged();
break;
}
// The ListView handles ALL drag events all the time. Fine for now since we don't need to
// drag -> drop outside of the ListView.
return true;
}
private void updateDataSetWithDrop(int fromRow, int toRow) {
log("updateDataSetWithDrop fromRow %d and toRow %d", fromRow, toRow);
sIconsForListItems[fromRow]--;
sIconsForListItems[toRow]++;
}
// NOTE: The DragEvent in local to DragDropListView, as are children coordinates
private void updateCurrentDropZoneView(DragEvent event) {
View previousDropZoneView = mCurrentDropZoneView;
mCurrentDropZoneView = findFrontmostDroppableChildAt(event.getX(), event.getY());
log("mCurrentDropZoneView updated to %d for x/y : %f/%f with action %d",
mCurrentDropZoneView == null ? -1 : indexOfChild(mCurrentDropZoneView) + getFirstVisiblePosition(),
event.getX(), event.getY(), event.getAction());
if (mCurrentDropZoneView != previousDropZoneView) {
if (previousDropZoneView != null) previousDropZoneView.setSelected(false);
if (mCurrentDropZoneView != null) mCurrentDropZoneView.setSelected(true);
}
}
}
/**
* The next four methods are utility methods taken from Android Source Code. Most are package-private on View
* or ViewGroup so I'm forced to replicate them here. Original source can be found:
* http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.0_r1/android/view/ViewGroup.java#ViewGroup.findFrontmostDroppableChildAt%28float%2Cfloat%2Candroid.graphics.PointF%29
*/
private View findFrontmostDroppableChildAt(float x, float y) {
int childCount = this.getChildCount();
for(int i=0; i<childCount; i++)
{
View child = getChildAt(i);
if (isTransformedTouchPointInView(x, y, child)) {
return child;
}
}
return null;
}
static public boolean isTransformedTouchPointInView(float x, float y, View child) {
PointF point = new PointF(x, y);
transformPointToViewLocal(point, child);
return pointInView(child, point.x, point.y);
}
static public void transformPointToViewLocal(PointF pointToModify, View child) {
pointToModify.x -= child.getLeft();
pointToModify.y -= child.getTop();
}
static public boolean pointInView(View v, float localX, float localY) {
return localX >= 0 && localX < (v.getRight() - v.getLeft())
&& localY >= 0 && localY < (v.getBottom() - v.getTop());
}
static final int[] sIconsForListItems;
static final int NUM_LIST_ITEMS = 50;
static final int MAX_NUM_ICON_PER_ELEMENT = 8;
static {
sIconsForListItems = new int[NUM_LIST_ITEMS];
for (int i=0; i < NUM_LIST_ITEMS; i++)
{
sIconsForListItems[i] = (getRand(MAX_NUM_ICON_PER_ELEMENT));
}
}
private static final String TAG = DragDropListView.class.getSimpleName();
private static void log(String format, Object... args) {
Log.d(TAG, String.format(format, args));
}
很多评论,希望代码是自文档化的。一些注意事项:
关于android - 如何使列表元素在滚动后获得 DragEvents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29825676/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解