Reputation: 49
How can I change the stroke width of a rectangle button when I press the button?
I have created a xml file in drawable folder for my custom button.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="9dp"/>
<gradient
android:angle="45"
android:centerX="9%"
android:centerColor="#84edb2"
android:startColor="#07e7cb"
android:endColor="#b0ede3"
android:type="linear"
/>
<size
android:width="40dp"
android:height="30dp"
/>
<stroke
android:width="2dp" // I want to change this programmatically.
android:color="#2f7E87"
/>
</shape>
Below is my java code. I want to change the button's stroke width when I press the button.
public static void buttonEffect(View button){
button.setOnTouchListener(new View.OnTouchListener() {
ShapeDrawable circle = new ShapeDrawable( new OvalShape() );
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Button view = (Button) v;
int col = Color.parseColor("#40E0D0");
view.getBackground().setColorFilter(col, PorterDuff.Mode.SCREEN);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP:
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
Button view = (Button) v;
view.getBackground().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
});
}
Upvotes: 2
Views: 2652
Reputation: 2660
It is based on @Dương Nguyễn Văn answer.
You have a button with the default stroke width of 2dp. Now you want its stroke width to change to 4dp when you press it.
So, you create two drawable files: bg_button_2.xml (stroke width = 2dp), and bg_button_4.xml (stroke width = 4dp).
Now you can change its background programmatically.
button.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
button.setBackgroundResource(R.drawable.bg_button_4);
}
});
Upvotes: 1
Reputation: 2048
Try below solution, It'll help you to solve your problem hopefully.
Here is a screenshot, Have a look
GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.red_500),
ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.red_500)});
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke((int)0.5, ContextCompat.getColor(this, R.color.black));
gd.setCornerRadius(8f);
gd.setBounds(2, 2, 2, 2);
btnCreateUser.setBackground(gd);
When you click your button, set width of stroke in this line according to your requirement, So that you don't have to use xml anymore
i.e: gd.setStroke((int)1, ContextCompat.getColor(this, R.color.black));
i.e: gd.setStroke((int)3, ContextCompat.getColor(this, R.color.black));
Upvotes: 3
Reputation: 418
I think solution is : + Create two shape drawable with difference size stroke. + When touch into button, just change background to other drawable like you done.
Upvotes: 2