3

我正在尝试制作一个上下文相关的ActionBar. 我使用了 android devpage 中的示例,但我仍然没有让它工作。我在 onitemlongclick 上设置了一个事件监听器,但setSelected(true)它似乎没有做任何事情。我知道该事件被触发,因为它actionmode已打开,但它没有选择任何项目。

longclicklistener是在 a 中fragment,由 a在一个活动中持有,该viewpager活动持有 的几个实例fragment。我希望能够从页面中选择项目,然后对选择进行一些操作。

我当前的代码:

片段:

AdapterView.OnItemLongClickListener onLongClick = new AdapterView.OnItemLongClickListener() {
    // Called when the user long-clicks on someView
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view,
            int i, long l) {
        MainActivity parent = (MainActivity)getActivity();
        if (parent.actionMode != null) {
            return false;
        }

        parent.actionMode = getActivity().startActionMode(parent.actionModeCallback);
        view.setSelected(true);
        return true;
    }
};

活动中的动作模式回调

public ActionMode.Callback actionModeCallback = new ActionMode.Callback() {

    // Called when the action mode is created; startActionMode() was called
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Inflate a menu resource providing context menu items
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.contextual_actionbar, menu);
        return true;
    }

    // Called each time the action mode is shown. Always called after onCreateActionMode, but
    // may be called multiple times if the mode is invalidated.
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false; // Return false if nothing is done
    }

    // Called when the user selects a contextual menu item
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_remove_list:
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }

    // Called when the user exits the action mode
    @Override
    public void onDestroyActionMode(ActionMode mode) {
        actionMode = null;
    }
};
4

1 回答 1

0

这是一个旧帖子,但对于所有新人......

对于设置选择时更改颜色的视图,您需要使用 颜色状态列表。颜色状态列表是一个 xml 资源文件,它根据视图所处的状态指定应应用哪种样式(选定是这些状态之一)。像这样的东西:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:color="@color/textColor" android:drawable="@color/Background" android:state_selected="true"/>
<item android:color="@color/textColor" android:drawable="@color/Background"/>

</selector>

在此处保存 XML 文件:res/color/filename.xml.

您必须在此 XML 资源的视图上设置您的android:background(您需要根据状态更改的任何属性,即)。android:textColor

然后,当您setSelected(true)应用适当的样式时。请注意,@drawable用于背景颜色,而@color用于其他组件,例如文本颜色。

于 2019-05-01T12:24:51.967 回答