Ralph Canapa
Ralph Canapa

Reputation: 640

In Unity 2021.2, using UI Toolkit features, how do I effect click-and-hold to a child Button of a list-item in a ListView?

I'm relatively new to Unity and I'm trying to build an in-game reorderable list using the UI Toolkit features.

I'm populating a ListView element with a Visual Tree Asset that is a composite of several Label and Button elements.

I would like to be able to click-and-hold a button (perhaps on the left-side) in the list-item and then drag the list-item, up or down, to the position I want in the list.

enter image description here

I was able to successfully bind the clickable.clicked function to a list-item child Button using the following code:

Action<VisualElement, int> bindItem = (e, i) => {
    var reorder_button = e.Q<Button>("reorder_button");
    if (reorder_button != null) reorder_button.clickable.clicked += () => ReorderClicked(e);
};

where the function called is:

void ReorderClicked(VisualElement ve)
{
    var title = ve.Q<Label>("title");
    Debug.Log("Clicked " + title.text);
};

This works as expected but how would I expand on this to accommodate click-and-hold or a mouse-down / mouse-up event?

It was suggested that I use the features in Unity for dragging events but I don't see a way of implementing this in the UI Toolkit framework.

Upvotes: 3

Views: 1707

Answers (1)

Aidenhjj
Aidenhjj

Reputation: 1289

I'm also new to Unity, but found a couple of solutions to this. It looks like you can add custom drag handlers by inheriting the PointerManipulator or MouseManipulator classes (see here for example that almost works as-is):

Action<VisualElement, int> bindItem = (e, i) =>
{
    ...
    e.AddManipulator(new DragAndDropManipulator(e));
}

You'd have to alter the implementation of PointerCaptureOutHandler from slot based to list ordering.

However, it appears that this behaviour is built into Unity (at least in my version - 2021.3.12f1). ListView has a reorderable property that you can set to true to enable drag and drop reordering. You can add drag animations by setting reorderMode to Animated.

Original source from unity forum.

Upvotes: 0

Related Questions