繁体   English   中英

如何在 Android 中以编程方式设置按钮边框颜色?

[英]How to set a button border color programmatically in Android?

我想在 Android 中有一个按钮边框颜色不同的按钮。

        Button Bt = new Button(this);
        Bt.setId(i+1);
        Bt.setBackgroundColor(getResources().getColor(R.color.white)) ;
        Bt.setText(restList.get(i));
        Bt.setLayoutParams(params3);
        Bt.setTextColor(Color.parseColor("gray"));
        layout.addView(Bt);

我如何以编程方式执行此操作?

 yourButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShapeDrawable shapedrawable = new ShapeDrawable();
                shapedrawable.setShape(new RectShape());
                shapedrawable.getPaint().setColor(Color.RED);
                shapedrawable.getPaint().setStrokeWidth(10f);
                shapedrawable.getPaint().setStyle(Style.STROKE);     
                yourButton.setBackground(shapedrawable);
            }
        });

试试这个,但我不确定 100%

您可以为此创建一个布局。 在您的代码中:

your_button.setBackgroundResource(R.drawable.your_layout);

your_layout - drawable 中的 XML 文件,例如:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <padding android:left="10dp"
        android:right="10dp"
        android:top="10dp"
        android:bottom="10dp"/>
    <stroke
        android:width="1dp"
        android:color="@color/colorPrimary" />
</shape>`

使用带有方法setStrokeColor()setStrokeWidth()MaterialButton ,比创建 Drawables 更容易

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM