Android 选择textview时,如何显示弹出窗口而不是CAB?

Android 选择textview时,如何显示弹出窗口而不是CAB?,android,textview,android-popupwindow,android-actionmode,Android,Textview,Android Popupwindow,Android Actionmode,我正在制作一个阅读应用程序,它有一个全屏活动。 当用户选择文本部分时,会出现一个带有复制选项的上下文操作栏。这是默认行为。但此操作栏会阻止它下面的文本,因此用户无法选择它 我想显示一个如下所示的弹出窗口。 我尝试从onCreateActionMode返回false,但当我这样做时,我也无法选择文本 我想知道是否有一种标准的方法来实现这一点,因为许多阅读应用程序都使用这种设计。我不知道Play Books是如何实现这一点的,但您可以创建一个,并根据选定的文本和一点数学计算它的位置。基本上,我们将

我正在制作一个阅读应用程序,它有一个全屏活动。
当用户选择文本部分时,会出现一个带有复制选项的
上下文操作栏
。这是默认行为。但此操作栏会阻止它下面的文本,因此用户无法选择它

我想显示一个如下所示的弹出窗口。

我尝试从
onCreateActionMode
返回
false
,但当我这样做时,我也无法选择文本


我想知道是否有一种标准的方法来实现这一点,因为许多阅读应用程序都使用这种设计。

我不知道Play Books是如何实现这一点的,但您可以创建一个,并根据选定的文本和一点数学计算它的位置。基本上,我们将:

  • 计算选定文本的边界
  • 计算
    PopupWindow的边界和初始位置
  • 计算两者之间的差异
  • PopupWindow
    偏移到选定文本上方或下方的水平/垂直静止中心
计算选择范围

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
:

使用高光的表示形式填充指定路径 在指定的偏移之间。这通常是一个矩形或矩形 可能不连续的矩形集。如果开始和结束是 同样,返回的路径为空

因此,在我们的例子中,指定的偏移量将是选择的开始和结束,可以使用and找到。为方便起见,
TextView
为我们提供了

现在我们已经有了一个选定的文本边界,我们可以选择相对于它放置
PopupWindow
的位置。在这种情况下,我们将沿选定文本的顶部或底部水平居中,这取决于显示弹出窗口的空间大小

计算初始弹出窗口坐标

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
接下来,我们需要计算弹出内容的边界。要做到这一点,我们首先需要调用,但是我们膨胀的
视图的边界不会立即可用,因此我建议使用a来等待它们变为可用

popupWindow.showAtLocation(yourTextView, Gravity.TOP, 0, 0)
弹出窗口。显示位置
要求:

  • 用于从中检索有效内容的
    视图,该视图仅唯一标识要放置弹出窗口的
    窗口
  • 可选重力,但在本例中为
    gravity.TOP
  • 可选的x/y偏移
因为在弹出内容布局完成之前,我们无法确定x/y偏移,所以我们将首先将其放置在默认位置。如果您试图调用<代码> PopupWindow。在“代码> >视图< /C> >之前,SuffTestPosie<代码>已被设置,您将收到A,因此您可以考虑使用<代码> VIELTReEvist.OnLogBayayOutListNo.<代码>来避免这一点,但当您选择文本并旋转设备时,它大多出现。p>
    final Rect cframe = new Rect();
    final int[] cloc = new int[2];
    popupContent.getLocationOnScreen(cloc);
    popupContent.getLocalVisibleRect(cbounds);
    popupContent.getWindowVisibleDisplayFrame(cframe);

    final int scrollY = ((View) yourTextView.getParent()).getScrollY();
    final int[] tloc = new int[2];
    yourTextView.getLocationInWindow(tloc);

    final int startX = cloc[0] + cbounds.centerX();
    final int startY = cloc[1] + cbounds.centerY() - (tloc[1] - cframe.top) - scrollY;
  • 将返回弹出内容的x/y坐标
  • 将返回弹出内容的边界
  • 将向我们返回偏移量以适应操作栏(如果存在)
  • 将返回我们的
    TextView
    所在的任何滚动容器的
    y
    偏移量(
    ScrollView
  • 将返回我们的
    文本视图的
    y
    偏移量,以防操作栏将其向下推一点
一旦我们获得了所需的所有信息,我们就可以计算弹出内容的最终起始x/y,然后用它来计算它们与所选文本
Rect
之间的差异,这样我们就可以到达新的位置

计算偏移弹出坐标

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
-1
此处仅表示我们为
弹出窗口提供的默认宽度/高度,在本例中

侦听选择更改

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
我们希望每次更改所选文本时,
PopupWindow
都会更新

/** An {@link ActionMode.Callback} used to remove all action items from text selection */
static final class EmptyActionMode extends SimpleActionModeCallback {

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Return true to ensure the text is still selectable
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // Remove all action items to provide an actionmode-less selection
        menu.clear();
        return true;
    }

}
监听选择更改的一种简单方法是将
TextView
子类化,并提供对的回调

侦听滚动更改

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
如果您在滚动容器(如
ScrollView
)中有
TextView
,您可能还需要监听滚动更改,以便在滚动时锚定弹出窗口。监听这些内容的一个简单方法是将
ScrollView
子类化,并提供对

创建一个空的

正如您在文章中提到的,我们需要返回
true
,以便文本保持可选性。但是我们还需要调用,以便删除您在
操作模式中为所选文本找到的所有项目

/** An {@link ActionMode.Callback} used to remove all action items from text selection */
static final class EmptyActionMode extends SimpleActionModeCallback {

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Return true to ensure the text is still selectable
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // Remove all action items to provide an actionmode-less selection
        menu.clear();
        return true;
    }

}
现在,我们可以使用来应用自定义的
操作模式
SimpleActionModeCallback
是一个自定义类,它只为
ActionMode.Callback
提供存根,类似于

布局

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);
这是我们正在使用的
活动
布局:

<your.package.name.NotifyingScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/notifying_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <your.package.name.NotifyingSelectionTextView
        android:id="@+id/notifying_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:textIsSelectable="true"
        android:textSize="20sp" />

</your.package.name.NotifyingScrollView>
把它全部带来

因此,现在我们已经:

  • 计算选定的文本边界
  • 计算了弹出窗口的边界
  • 计算差异并确定弹出偏移量
  • 提供了一种侦听滚动更改和选择更改的方法
  • 创建了我们的
    活动
    和弹出式布局
将所有内容组合在一起可能看起来像:

public class ActionModePopupActivity extends AppCompatActivity
        implements ScrollChangeListener, SelectionChangeListener {

    private static final int DEFAULT_WIDTH = -1;
    private static final int DEFAULT_HEIGHT = -1;

    private final Point currLoc = new Point();
    private final Point startLoc = new Point();

    private final Rect cbounds = new Rect();
    private final PopupWindow popupWindow = new PopupWindow();
    private final ActionMode.Callback emptyActionMode = new EmptyActionMode();

    private NotifyingSelectionTextView yourTextView;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action_mode_popup);

        // Initialize the popup content, only add it to the Window once we've selected text
        final LayoutInflater inflater = LayoutInflater.from(this);
        popupWindow.setContentView(inflater.inflate(R.layout.view_action_mode_popup, null));
        popupWindow.setWidth(WRAP_CONTENT);
        popupWindow.setHeight(WRAP_CONTENT);

        // Initialize to the NotifyingScrollView to observe scroll changes
        final NotifyingScrollView scroll
                = (NotifyingScrollView) findViewById(R.id.notifying_scroll_view);
        scroll.setScrollChangeListener(this);

        // Initialize the TextView to observe selection changes and provide an empty ActionMode
        yourTextView = (NotifyingSelectionTextView) findViewById(R.id.notifying_text_view);
        yourTextView.setText(IPSUM);
        yourTextView.setSelectionChangeListener(this);
        yourTextView.setCustomSelectionActionModeCallback(emptyActionMode);
    }

    @Override
    public void onScrollChanged() {
        // Anchor the popup while the user scrolls
        if (popupWindow.isShowing()) {
            final Point ploc = calculatePopupLocation();
            popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        }
    }

    @Override
    public void onTextSelected() {
        final View popupContent = popupWindow.getContentView();
        if (popupWindow.isShowing()) {
            // Calculate the updated x/y pop coordinates
            final Point ploc = calculatePopupLocation();
            popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        } else {
        // Add the popup to the Window and position it relative to the selected text bounds
        ViewUtils.onGlobalLayout(yourTextView, () -> {
            popupWindow.showAtLocation(yourTextView, TOP, 0, 0);
            // Wait for the popup content to be laid out
            ViewUtils.onGlobalLayout(popupContent, () -> {
                final Rect cframe = new Rect();
                final int[] cloc = new int[2];
                popupContent.getLocationOnScreen(cloc);
                popupContent.getLocalVisibleRect(cbounds);
                popupContent.getWindowVisibleDisplayFrame(cframe);

                final int scrollY = ((View) yourTextView.getParent()).getScrollY();
                final int[] tloc = new int[2];
                yourTextView.getLocationInWindow(tloc);

                final int startX = cloc[0] + cbounds.centerX();
                final int startY = cloc[1] + cbounds.centerY() - (tloc[1] - cframe.top) - scrollY;
                startLoc.set(startX, startY);

                final Point ploc = calculatePopupLocation();
                popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
            });
        });
        }
    }

    @Override
    public void onTextUnselected() {
        popupWindow.dismiss();
    }

    /** Used to calculate where we should position the {@link PopupWindow} */
    private Point calculatePopupLocation() {
        final ScrollView parent = (ScrollView) yourTextView.getParent();

        // Calculate the selection start and end offset
        final int selStart = yourTextView.getSelectionStart();
        final int selEnd = yourTextView.getSelectionEnd();
        final int min = Math.max(0, Math.min(selStart, selEnd));
        final int max = Math.max(0, Math.max(selStart, selEnd));

        // Calculate the selection bounds
        final RectF selBounds = new RectF();
        final Path selection = new Path();
        yourTextView.getLayout().getSelectionPath(min, max, selection);
        selection.computeBounds(selBounds, true /* this param is ignored */);

        // Retrieve the center x/y of the popup content
        final int cx = startLoc.x;
        final int cy = startLoc.y;

        // Calculate the top and bottom offset of the popup relative to the selection bounds
        final int popupHeight = cbounds.height();
        final int textPadding = yourTextView.getPaddingLeft();
        final int topOffset = Math.round(selBounds.top - cy);
        final int btmOffset = Math.round(selBounds.bottom - (cy - popupHeight));

        // Calculate the x/y coordinates for the popup relative to the selection bounds
        final int scrollY = parent.getScrollY();
        final int x = Math.round(selBounds.centerX() + textPadding - cx);
        final int y = Math.round(selBounds.top - scrollY < cy ? btmOffset : topOffset);
        currLoc.set(x, y - scrollY);
        return currLoc;
    }

    /** An {@link ActionMode.Callback} used to remove all action items from text selection */
    static final class EmptyActionMode extends SimpleActionModeCallback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return true;
        }

    }

}

结果

    // Calculate the top and bottom offset of the popup relative to the selection bounds
    final int popupHeight = cbounds.height();
    final int textPadding = yourTextView.getPaddingLeft();
    final int topOffset = Math.round(selBounds.top - startY);
    final int btmOffset = Math.round(selBounds.bottom - (startY - popupHeight));

    // Calculate the x/y coordinates for the popup relative to the selection bounds
    final int x = Math.round(selBounds.centerX() + textPadding - startX);
    final int y = Math.round(selBounds.top - scrollY < startY ? btmOffset : topOffset);

额外的

我不会讨论如何将单击侦听器附加到弹出操作,可能有几种方法可以通过不同的计算和实现实现相同的效果。但我要提到的是,如果您想要检索所选文本,然后对其进行处理

无论如何,我希望
public class ActionModePopupActivity extends AppCompatActivity
        implements ScrollChangeListener, SelectionChangeListener {

    private static final int DEFAULT_WIDTH = -1;
    private static final int DEFAULT_HEIGHT = -1;

    private final Point currLoc = new Point();
    private final Point startLoc = new Point();

    private final Rect cbounds = new Rect();
    private final PopupWindow popupWindow = new PopupWindow();
    private final ActionMode.Callback emptyActionMode = new EmptyActionMode();

    private NotifyingSelectionTextView yourTextView;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action_mode_popup);

        // Initialize the popup content, only add it to the Window once we've selected text
        final LayoutInflater inflater = LayoutInflater.from(this);
        popupWindow.setContentView(inflater.inflate(R.layout.view_action_mode_popup, null));
        popupWindow.setWidth(WRAP_CONTENT);
        popupWindow.setHeight(WRAP_CONTENT);

        // Initialize to the NotifyingScrollView to observe scroll changes
        final NotifyingScrollView scroll
                = (NotifyingScrollView) findViewById(R.id.notifying_scroll_view);
        scroll.setScrollChangeListener(this);

        // Initialize the TextView to observe selection changes and provide an empty ActionMode
        yourTextView = (NotifyingSelectionTextView) findViewById(R.id.notifying_text_view);
        yourTextView.setText(IPSUM);
        yourTextView.setSelectionChangeListener(this);
        yourTextView.setCustomSelectionActionModeCallback(emptyActionMode);
    }

    @Override
    public void onScrollChanged() {
        // Anchor the popup while the user scrolls
        if (popupWindow.isShowing()) {
            final Point ploc = calculatePopupLocation();
            popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        }
    }

    @Override
    public void onTextSelected() {
        final View popupContent = popupWindow.getContentView();
        if (popupWindow.isShowing()) {
            // Calculate the updated x/y pop coordinates
            final Point ploc = calculatePopupLocation();
            popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        } else {
        // Add the popup to the Window and position it relative to the selected text bounds
        ViewUtils.onGlobalLayout(yourTextView, () -> {
            popupWindow.showAtLocation(yourTextView, TOP, 0, 0);
            // Wait for the popup content to be laid out
            ViewUtils.onGlobalLayout(popupContent, () -> {
                final Rect cframe = new Rect();
                final int[] cloc = new int[2];
                popupContent.getLocationOnScreen(cloc);
                popupContent.getLocalVisibleRect(cbounds);
                popupContent.getWindowVisibleDisplayFrame(cframe);

                final int scrollY = ((View) yourTextView.getParent()).getScrollY();
                final int[] tloc = new int[2];
                yourTextView.getLocationInWindow(tloc);

                final int startX = cloc[0] + cbounds.centerX();
                final int startY = cloc[1] + cbounds.centerY() - (tloc[1] - cframe.top) - scrollY;
                startLoc.set(startX, startY);

                final Point ploc = calculatePopupLocation();
                popupWindow.update(ploc.x, ploc.y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
            });
        });
        }
    }

    @Override
    public void onTextUnselected() {
        popupWindow.dismiss();
    }

    /** Used to calculate where we should position the {@link PopupWindow} */
    private Point calculatePopupLocation() {
        final ScrollView parent = (ScrollView) yourTextView.getParent();

        // Calculate the selection start and end offset
        final int selStart = yourTextView.getSelectionStart();
        final int selEnd = yourTextView.getSelectionEnd();
        final int min = Math.max(0, Math.min(selStart, selEnd));
        final int max = Math.max(0, Math.max(selStart, selEnd));

        // Calculate the selection bounds
        final RectF selBounds = new RectF();
        final Path selection = new Path();
        yourTextView.getLayout().getSelectionPath(min, max, selection);
        selection.computeBounds(selBounds, true /* this param is ignored */);

        // Retrieve the center x/y of the popup content
        final int cx = startLoc.x;
        final int cy = startLoc.y;

        // Calculate the top and bottom offset of the popup relative to the selection bounds
        final int popupHeight = cbounds.height();
        final int textPadding = yourTextView.getPaddingLeft();
        final int topOffset = Math.round(selBounds.top - cy);
        final int btmOffset = Math.round(selBounds.bottom - (cy - popupHeight));

        // Calculate the x/y coordinates for the popup relative to the selection bounds
        final int scrollY = parent.getScrollY();
        final int x = Math.round(selBounds.centerX() + textPadding - cx);
        final int y = Math.round(selBounds.top - scrollY < cy ? btmOffset : topOffset);
        currLoc.set(x, y - scrollY);
        return currLoc;
    }

    /** An {@link ActionMode.Callback} used to remove all action items from text selection */
    static final class EmptyActionMode extends SimpleActionModeCallback {

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Return true to ensure the yourTextView is still selectable
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // Remove all action items to provide an actionmode-less selection
            menu.clear();
            return true;
        }

    }

}
public static float lerp(float a, float b, float v) {
    return a + (b - a) * v;
}
private static final int DEFAULT_ANIM_DUR = 350;
private static final int DEFAULT_ANIM_DELAY = 500;

@Override
public void onTextSelected() {
    final View popupContent = popupWindow.getContentView();
    if (popupWindow.isShowing()) {
        // Calculate the updated x/y pop coordinates
        popupContent.getHandler().removeCallbacksAndMessages(null);
        popupContent.postDelayed(() -> {
            // The current x/y location of the popup
            final int currx = currLoc.x;
            final int curry = currLoc.y;
            // Calculate the updated x/y pop coordinates
            final Point ploc = calculatePopupLocation();
            currLoc.set(ploc.x, ploc.y);
            // Linear interpolate between the current and updated popup coordinates
            final ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
            anim.addUpdateListener(animation -> {
                final float v = (float) animation.getAnimatedValue();
                final int x = Math.round(AnimUtils.lerp(currx, ploc.x, v));
                final int y = Math.round(AnimUtils.lerp(curry, ploc.y, v));
                popupWindow.update(x, y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
            });
            anim.setDuration(DEFAULT_ANIM_DUR);
            anim.start();
        }, DEFAULT_ANIM_DELAY);
    } else {
        ...
    }
}