How to set a button border color programmatically in Android?
Asked Answered
H

4

8

I want to have a button in Android with differnt color for button border.

        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);

How can I do this programmatically?

Hornbeam answered 3/12, 2015 at 20:3 Comment(0)
T
19
 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);
            }
        });

try this but i am not sure 100%

Turntable answered 3/12, 2015 at 20:53 Comment(0)
C
1

You can create a layout for this. in your code:

your_button.setBackgroundResource(R.drawable.your_layout);

your_layout - XML file in your drawable, like:

<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>`

Catling answered 24/11, 2019 at 14:31 Comment(0)
N
0

Use MaterialButton which comes with methods setStrokeColor() and setStrokeWidth() and is easier than creating Drawables

Nealy answered 18/1, 2023 at 8:18 Comment(0)
F
0

GradientDrawable worked for me:

imageView.imageTintList = null
val drawable = GradientDrawable().apply {
     shape = GradientDrawable.OVAL
     setColor(color)
     setStroke(strokeSize, strokeColor)
}
imageView.setImageDrawable(drawable)
Fleshpots answered 6/10, 2023 at 4:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.