Android Toggle Button自定义大小/填充/间距

And*_*cus 6 java layout android togglebutton

我正在尝试为Android Toggle Buttons创建自定义样式.更改颜色和文本没有问题,但我无法更改大小/填充/间距或其他任何内容,使它们默认显示为不必要的大.我将wrap_content和padding以及margin的高度设置为0,但是按钮的大小仍然与默认的Toggle Button一样大.

你是否有人知道我要更改哪些参数以删除按钮的文本和边框之间不必要的间距?

这是我想要实现的图像的链接.从左到右:默认ToggleButton,我当前的ToggleButton和我想要的ToggleButton.

这是我的代码(因为我动态添加这些按钮,没有xml)

ToggleButton button = new ToggleButton(getContext());
button.setLayoutParams(new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
button.setId(IDCreator.getID());
button.setText(tag);
button.setTextOff(tag);
button.setTextOn(tag);
button.setGravity(Gravity.LEFT);
button.setPadding(0, 0, 0, 0);
button.setBackground(getContext().getResources().getDrawable(R.drawable.toggle_selector));
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.亲切的问候.

编辑:图像和代码

小智 1

如果您只是想更改 中文本的呈现方式ToggleButton,那么您需要调整按钮 XML 中的android:padding和参数。android:gravity

要更改内边距,您首先需要使文本不再默认居中(因为当它居中时,内边距无法生效)。您可以通过android:gravity类似于 CSS 中的 text-align 的参数来完成此操作。

例如;

<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left">
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)

这会将文本对齐到切换按钮的左侧。但是,默认情况下,这也会将其对齐到顶部,因为重力会影响 x 轴和 y 轴。

如果要垂直居中、水平左对齐,可以执行以下操作:

<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left|center">
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)

这将使您的它垂直居中,但在水平刻度上完全设置在左侧。这将使文本出现在按钮边缘上并且看起来没有吸引力。您需要将对齐方式与文本填充结合使用,以便将其准确地放置在您想要的位置。

例如:

<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding_left="10dp"
android:gravity="left|center">
</ToggleButton>
Run Code Online (Sandbox Code Playgroud)

只会在左侧添加填充,这意味着您可以将其设置为距边框尽可能远。

您可以尝试调整每侧的填充和重力,以便根据需要缩放文本,但这将是控制 ToggleButton 内部文本对齐方式的最佳方法。