Android 以编程方式创建具有大纲样式的MaterialButton

Android 以编程方式创建具有大纲样式的MaterialButton,android,android-layout,material-design,android-button,androidx,Android,Android Layout,Material Design,Android Button,Androidx,我希望以编程方式创建一个按钮,如以下设计准则中所定义: 在XML中,我可以使用这段布局XML实现这一点: <com.google.android.material.button.MaterialButton android:id="@+id/buttonGetStarted" style="@style/Widget.MaterialComponents.Button.OutlinedButton" android:text="@string/title_shor

我希望以编程方式创建一个按钮,如以下设计准则中所定义:

在XML中,我可以使用这段布局XML实现这一点:

<com.google.android.material.button.MaterialButton
    android:id="@+id/buttonGetStarted"
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    android:text="@string/title_short_intro" />
但这不会导致大纲变体:

您可以使用以下命令:

MaterialButton testSignIn = new MaterialButton(context, null, R.attr.borderlessButtonStyle);
String buttonText = "Sign-in & empty test account";
testSignIn.setText(buttonText);

MaterialButton
具有用于设置轮廓的
strokeColor
strokeWidth

val _strokeColor = getColorStateList(R.styleable.xxx_strokeColor)
val _strokeWidth = getDimensionPixelSize(R.styleable.xxx_strokeWidth, 0)

button = MaterialButton(context).apply {
    layoutParams = LayoutParams(MATCH_PARENT, WRAP_PARENT)
    strokeColor = _strokeColor
    strokeWidth = _strokeWidth
}

创建略图按钮布局略图按钮.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Widget.MaterialComponents.Button.OutlinedButton"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</com.google.android.material.button.MaterialButton>
如果要应用轮廓按钮,可以在构造函数中使用
R.attr.materialButtonOutlinedStyle
属性样式:

MaterialButton outlinedButton = new MaterialButton(context,null, R.attr.materialButtonOutlinedStyle);
outlinedButton.setText("....");

如果我没有错的话,它是:
style=“@style/Widget.AppCompat.Button.Borderless.Colored
看看这是否回答了你的问题。刚刚测试了这个(将我代码中的R.style.Widget\u MaterialComponents\u Button\u OutlinedButton更改为R.style.Widget\u AppCompat\u Button\u Borderless\u Colored)。这没有区别。添加这两个
style=”@style/Widget.AppCompat.Button.Borderless.Colored
转换为xml和java kotlin中的相同格式,然后再试一次。你有没有发现这个问题?@masterwork,没有。。。仍然使用基于XML的布局作为解决方案(请随时更新我,以防找到解决方案)。
R.attr.borderlessButtonStyle
不创建大纲按钮。我认为正确的属性应该是
R.attr.materialButtonOutlinedStyle
谢谢,我使用的是普通类
按钮
,因为他们声称它们可以转换它们,但当通过代码完成时,我不会神奇地转换它们,只从xml进行转换。这对我很有效。要充气的Kotlin代码:val b:MaterialButton=this.layoutInflater.inflate(R.layout.outline_button,null)作为MaterialButton完美工作,这里是Xamarin.Android:new MaterialButton(Context,null,Resource.Attribute.materialButtonOutlinedStyle);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MaterialButton button = (MaterialButton)inflater.inflate(R.layout.outlined_button, vg, false);
MaterialButton outlinedButton = new MaterialButton(context,null, R.attr.materialButtonOutlinedStyle);
outlinedButton.setText("....");