我也在努力寻找解决方案。找到了。您需要为没有插入的按钮创建一个样式,并在您的应用主题的materialButtonOutlinedStyle attr 中定义它。不要忘记在 MaterialButton ctor 中指定此类 attr。像这样:
styles.xml:
<style name="AppTheme" parent="Theme.MaterialComponents" >
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
< ... />
<!-- The following defines the OutlinedButton style with your custom attrs -->
<item name="materialButtonOutlinedStyle">@style/Widget.MaterialComponents.Button.OutlinedButton.NoInsets</item>
</style>
<style name="Widget.MaterialComponents.Button.OutlinedButton.NoInsets"
parent="Widget.MaterialComponents.Button.OutlinedButton" >
<!-- Here you can customize the drawable insets! -->
<item name="android:insetTop">0dp</item>
<item name="android:insetBottom">0dp</item>
</style>
活动/代码/Java 中的任何内容:
private void addButtons() {
MaterialButtonToggleGroup buttonGroup = findViewById(R.id.preference_selection_button_group);
final ViewGroup.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
final int n = mEntries.length;
for (int i = 0; i < n; i++)
buttonGroup.addView(createChoiceButton(i, mEntries[i]), i, lp);
}
private View createChoiceButton(int index, CharSequence entry) {
final MaterialButton button = new MaterialButton(
getContext(),
null,
R.attr.materialButtonOutlinedStyle /** which points to your new OutlinedButton theme **/);
button.setId(index);
button.setText(entry);
return button;
}
布局:
<parentLayout ...>
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/preference_selection_button_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:singleSelection="true"
app:selectionRequired="true" />
</parentLayout>
此代码用于 VERTICAL MaterialButtonToggleGroup,结果如下: