android - 如何删除可检查菜单项的末尾填充?

标签 android android-menu android-checkbox overflow-menu

我有一个带有可检查菜单项的溢出菜单。我想将 CheckBox 一直对齐到最后,但我不知道如何做到这一点。

我的菜单定义如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:icon="@drawable/ic_baseline_more_vert_24"
        android:title=""
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/desktop_site"
                android:checkable="true"
                android:checked="false"
                android:icon="@drawable/ic_baseline_desktop_windows_24"
                android:title="Desktop site"
                app:showAsAction="never" />
        </menu>
    </item>
</menu>

Overflow menu

最佳答案

您可以为 CheckBox 创建自定义样式,并使用负值调整结束填充:

<style name="checkbox_style" parent="android:style/Widget.Holo.Light.CompoundButton.CheckBox">
    <item name="android:paddingRight">-7dp</item>
</style>

并将其应用到您应用的主题:

<item name="checkboxStyle">@style/checkbox_style</item>

enter image description here

注意:默认情况下,菜单项周围应该有一些边距;因此您无法将 checkBox 发送到远端,因为它的右边缘会被切割:

使用 -8dp 时:

enter image description here

因此,处理此问题时需要小心。

更新

but it affects all the CheckBoxes in my app

这需要在布局中的所有 CheckBoxes 中反转此填充;并且有以下选项:

  • 第一个选项:android:paddingRight="7dp"/android:paddingEnd="7dp" 添加到所有 CheckBoxes
  • 第二个选项:创建一个自定义 CheckBox 类并将此填充添加到其构造函数中;并使用这个自定义的 CheckBox 而不是默认的 CheckBox:
public class MyCheckBox extends AppCompatCheckBox {

    public MyCheckBox(Context context) {
        super(context);
        init();
    }

    public MyCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        int px = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                7f, // dp value
                getResources().getDisplayMetrics()
        );
        setPadding(0, 0, px, 0);
    }

    public MyCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


}

并使用它:

<!-- Add the full path of the customized CheckBox -->
<com.example.android......MyCheckBox   
    android:id="@+id/checkbox2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

提示:如果您的目标是 API-17+,请使用 android:paddingEnd 而不是 android:paddingRight

关于android - 如何删除可检查菜单项的末尾填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69606994/

相关文章:

android - Android ListView 中的弹出菜单问题

android - searchManager.getSearchableInfo(getComponentName()) 返回 null

android - 复选框颜色更改android

java - 选中 CheckBox 时更改 ListView 行中的文本颜色

c# - Android键盘覆盖文本框问题

java - 用Java创建一个文字游戏(字典文件组织问题)

java - 如何从中断处继续进行 Activity ?

android - 来自 Transformation 的数据绑定(bind) LiveData - Android Kotlin

android - 微调器作为 MenuItem 未由 findViewById 初始化

Android 可检查菜单项