I have a custom ImageButton class mimicing the ToggleButton's checked state based on this tutorial How to add a custom button state .
Everything works fine, when I have a state list drawable as the android:src attribute, but the custom state doesn't work with the ImageButton's android:background attribute.
Here is my code:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.ImageButton;
public class CheckableImageButton extends ImageButton implements Checkable {
private static final int[] STATE_CHECKED = {R.attr.state_checked};
private boolean mChecked = false;
public CheckableImageButton(Context context) {
super(context);
}
public CheckableImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if(mChecked){
mergeDrawableStates(drawableState, STATE_CHECKED);
}
return drawableState;
}
#Override
public boolean isChecked() {
return mChecked;
}
#Override
public void setChecked(boolean checked) {
mChecked = checked;
refreshDrawableState();
}
#Override
public void toggle() {
setChecked(!mChecked);
}
}
And the relevant snippet from the layout XML:
<com.my.package.view.CheckableImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="#drawable/header_button_bg"
android:padding="5dp"
android:src="#drawable/menu_button"
tools:ignore="ContentDescription" />
And the state list drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/my.package" >
<item android:state_pressed="true">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#ff000000" />
<gradient android:angle="-90" android:endColor="#d2914e" android:startColor="#906434" />
<corners android:radius="5dp" />
</shape>
</item>
<item app:state_checked="true">
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#ff000000" />
<gradient android:angle="-90" android:endColor="#d2914e" android:startColor="#906434" />
<corners android:radius="5dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<stroke android:width="1dp" android:color="#ff000000" />
<gradient android:angle="-90" android:endColor="#4f5b6c" android:startColor="#345b75" />
<corners android:radius="5dp" />
</shape>
</item>
</selector>
Another wonderful trait of eclipse probably..
When I tried to revert my code to the last working version by hand (the state list drawable in the android:src tag), it produced the same error. I reverted from the SVN repo, it worked. Then I made the exact same changes as before, character by character, no difference, and voilá, it works now!
So that's it, the code in the question is fully functional.
Related
MOCK UP
Requirement
I want to put custom button with selector.
Mock up is given above.
If anyone knows solution then share it.
Thank you.
basically you will need to create some new XML files and apply them to your Button element. As i can see from the mockup you will need a stroke and the background color with some shading effect applied, you can research more into the shading thing but the background color and the stroke is pretty straight forward.
Here is an example, done_rounded_btn.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="#drawable/zzzzzzzzz_btn_orange" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="#drawable/zzzzzzzzz_btn_orange" />
<item
android:state_focused="false"
android:state_enabled="false"
android:drawable="#drawable/zzzzzzzzz_btn_inactiv" />
<item android:drawable="#drawable/zzzzzzzzz_btn_black"/>
</selector>
for the selection part and then you create the custom drawables corresponding to the mockup.
An example, zzzzzzzzzz_btn_orange:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid
android:color="#color/done_color">
</solid>
<corners
android:bottomLeftRadius="3dp"
android:bottomRightRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp" />
</shape>
And then add it to your button as background, main.xml:
<Button
android:id="#+id/registers_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/done_rounded_btn"
android:text="#string/done_txt"
android:textColor="#color/white"
android:textSize="15sp" />
Hope this helps!
You can use this instead of standard Button and set selector as background in xml:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
/**
* Custom Shape Button which ignores touches on transparent background.
*/
public class ButtonWithUntouchableTransparentBg extends Button {
public ButtonWithUntouchableTransparentBg(Context context) {
this(context, null);
}
public ButtonWithUntouchableTransparentBg(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ButtonWithUntouchableTransparentBg(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDrawingCacheEnabled(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
// ignores touches on transparent background
if (isPixelTransparent(x, y))
return true;
else
return super.onTouchEvent(event);
}
/**
* #return true if pixel from (x,y) is transparent
*/
private boolean isPixelTransparent(int x, int y) {
Bitmap bmp = Bitmap.createBitmap(getDrawingCache());
int color = Color.TRANSPARENT;
try {
color = bmp.getPixel(x, y);
} catch (IllegalArgumentException e) {
// x or y exceed the bitmap's bounds.
// Reverts the View's internal state from a previously set "pressed" state.
setPressed(false);
}
// Ignores touches on transparent background.
if (color == Color.TRANSPARENT)
return true;
else
return false;
}
}
You can also create a shape that is using a selector inside. If your shape is just changing its color in different states, this is a lot cleaner.
color/color_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/blue_dark" android:state_pressed="true" />
<item android:color="#color/blue_light" />
</selector>
drawable/shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/color_selector" />
<corners android:bottomLeftRadius="6dip" android:bottomRightRadius="6dp" />
<padding android:bottom="0dip" android:left="0dip" android:right="0dip" android:top="0dip" />
</shape>
Button with rounded corners with two states (enabled/disabled):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/white" />
<stroke android:width="1dp" android:color="#color/orange" />
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/grey_card_background" />
<stroke android:width="1dp" android:color="#color/grey" />
</shape>
</item>
</selector>
inside your item put the shape in the selector XML
EX FROM MY CODE :
<!-- if pressed -->
<item android:state_pressed="true"><shape android:padding="10dp" android:shape="rectangle">
<solid android:color="#color/blue" />
<corners android:bottomLeftRadius="10dp" android:bottomRightRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp" />
</shape></item>
<!-- if not pressed -->
<item><shape android:padding="10dp" android:shape="rectangle">
<solid android:color="#color/Purbble" />
<corners android:bottomLeftRadius="10dp" android:bottomRightRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp" />
</shape></item>
I want to add text inside switches and expect toggle to completely cover the texts
I was able to achieve this in API 16 with below option
<Switch
android:textOff="off"
android:showText="true"
android:textOn="on"/>
However same switch looks odd in the higher version(i'm testing with API 27) where switch toggle is a round icon behind the text.
Is there a way i can fit the text inside the switch toggle using native library/methods.
I found this code in GitHub. After some addition and modification, I get what I need. This toggle button has YES NO text on it and works like switch button. You can give it a go.
public class ToggleButton extends RelativeLayout implements View.OnClickListener {
FrameLayout layout;
TextView toggleCircle;
View background_oval_off, background_oval_on;
int dimen;
private Boolean _crossfadeRunning = false;
private ObjectAnimator _oaLeft, _oaRight;
public ToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.toggle_button, this, true);
background_oval_off = findViewById(R.id.background_oval_off);
background_oval_on = findViewById(R.id.background_oval_on);
toggleCircle = findViewById(R.id.toggleCircle);
layout = (FrameLayout) findViewById(R.id.layout);
layout.setOnClickListener(this);
//get a pixel size for a particular dimension - will differ by device according to screen density
dimen = getResources().getDimensionPixelSize(R.dimen.toggle_width);
_oaLeft = ObjectAnimator.ofFloat(toggleCircle, "x", dimen / 2, 0).setDuration(250);
_oaRight = ObjectAnimator.ofFloat(toggleCircle, "x", 0, dimen / 2).setDuration(250);
//setState();
}
public ToggleButton(Context context) {
this(context, null);
}
public void setState(String answer) {
Log.d("simul", "ans - " + answer);
if (answer.equals("1")) {
toggleCircle.setTextColor(ContextCompat.getColor(getContext(), R.color.green));
toggleCircle.setX(dimen / 2);
_crossfadeViews(background_oval_off, background_oval_on, 1);
toggleCircle.setText("Yes");
} else {
toggleCircle.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
toggleCircle.setX(0);
_crossfadeViews(background_oval_on, background_oval_off, 1);
toggleCircle.setText("No");
}
}
private void _crossfadeViews(final View begin, View end, int duration) {
_crossfadeRunning = true;
end.setAlpha(0f);
end.setVisibility(View.VISIBLE);
end.animate().alpha(1f).setDuration(duration).setListener(null);
begin.animate().alpha(0f).setDuration(duration).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
begin.setVisibility(View.GONE);
_crossfadeRunning = false;
}
});
}
#Override
public void onClick(View view) {
if (_oaLeft.isRunning() || _oaRight.isRunning() || _crossfadeRunning) return;
if (toggleCircle.getText().equals("Yes")) {
_oaLeft.start();
_crossfadeViews(background_oval_on, background_oval_off, 110);
toggleCircle.setText("No");
toggleCircle.setTextColor(ContextCompat.getColor(getContext(), R.color.red));
mListener.toggleButtonClickListener("No");
} else {
_oaRight.start();
_crossfadeViews(background_oval_off, background_oval_on, 400);
toggleCircle.setText("Yes");
toggleCircle.setTextColor(ContextCompat.getColor(getContext(), R.color.green));
mListener.toggleButtonClickListener("Yes");
}
}
public ToggleButtonListener mListener = null;
public void setToggleButtonClickListener(ToggleButtonListener listener) {
mListener = listener;
}
public interface ToggleButtonListener {
public void toggleButtonClickListener(String content);
}
}
toogle_button_red_oval.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="#dimen/toggle_circle_diameter">
<shape android:shape="oval">
<solid android:color="#color/red"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
<item android:left="#dimen/toggle_circle_radius" android:right="#dimen/toggle_circle_radius">
<shape android:shape="rectangle">
<solid android:color="#color/red"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
<item android:left="#dimen/toggle_circle_diameter">
<shape android:shape="oval">
<solid android:color="#color/red"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
</layer-list>
toogle_button_green_oval.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:right="#dimen/toggle_circle_diameter">
<shape android:shape="oval">
<solid android:color="#color/green"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
<item android:left="#dimen/toggle_circle_radius" android:right="#dimen/toggle_circle_radius">
<shape android:shape="rectangle">
<solid android:color="#color/green"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
<item android:left="#dimen/toggle_circle_diameter">
<shape android:shape="oval">
<solid android:color="#color/green"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
</item>
</layer-list>
toogle_button_circle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#color/white"/>
<size
android:height="#dimen/toggle_circle_diameter"
android:width="#dimen/toggle_circle_diameter" />
</shape>
toogle_button.xml
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:id="#+id/layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<View
android:layout_width="#dimen/toggle_width"
android:layout_height="#dimen/toggle_height"
android:id="#+id/background_oval_off"
android:background="#drawable/toggle_button_black_oval" />
<View
android:layout_width="#dimen/toggle_width"
android:layout_height="#dimen/toggle_height"
android:id="#+id/background_oval_on"
android:background="#drawable/toggle_button_green_oval"
android:visibility="gone" />
<TextView
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:layout_width="#dimen/toggle_circle_diameter"
android:layout_height="#dimen/toggle_circle_diameter"
android:layout_gravity="center_vertical"
android:id="#+id/toggleCircle"
android:textSize="#dimen/toggle_text_size"
android:text="No"
android:background="#drawable/toggle_button_circle"/>
</FrameLayout>
</merge>
XML layout code
<package.name.ToggleButton
android:id="#+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</cpackage.name.ToggleButton>
Java Code :
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setToggleButtonClickListener(new ToggleButton.ToggleButtonListener() {
#Override
public void toggleButtonClickListener(String content) {
if (content.equals("Yes")) {
} else {
}
}
});
dimens.xml
<dimen name="toggle_width">100dp</dimen>
<dimen name="toggle_height">50dp</dimen>
<dimen name="toggle_circle_diameter">50dp</dimen>
<dimen name="toggle_circle_radius">25dp</dimen>
Sorry for this long long answer. I had to add all the code here. please let me know if anything missing here. :)
How to change text position for different button states?
On image you can see how its look like now:
drawable
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true">
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="4dp">
<shape android:shape="rectangle">
<solid android:color="#DCDBDB" />
<corners android:radius="7dp" />
<stroke android:width="1dp" android:color="#B1B1B1"/>
</shape>
</item>
<item android:bottom="4.5dp" android:left="1.5dp" android:right="1.5dp" android:top="5.5dp">
<shape android:shape="rectangle" android:gravity="bottom">
<solid android:color="#F2F1F1" />
<corners android:radius="6dp" />
<stroke android:width="1dp" android:color="#FFFFFF"/>
</shape>
</item>
</layer-list>
</item>
<item>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#DCDBDB" />
<corners android:radius="7dp" />
<stroke android:width="1dp" android:color="#B1B1B1"/>
</shape>
</item>
<item android:bottom="8.5dp" android:left="1.5dp" android:right="1.5dp" android:top="1.5dp">
<shape android:shape="rectangle">
<solid android:color="#F2F1F1" />
<corners android:radius="6dp" />
<stroke android:width="1dp" android:color="#FFFFFF"/>
</shape>
</item>
</layer-list>
</item>
</selector>
Few days ago I asked similar question - Android 3D button src padding, but for text I cant use this trick :/ (or dont know how).
You will need to create a custom Button and override the methods for changing it's state in order to customize it's gravity based on the current state.
For example here is the code for a custom Button whose text will jump to the bottom when it is pressed:
public class VariableGravityButton extends Button {
public VariableGravityButton(Context context) {
super(context);
}
public VariableGravityButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VariableGravityButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void setPressed(boolean pressed) {
if (pressed != isPressed()) {
setGravity(pressed ? Gravity.CENTER_HORIZONTAL |
Gravity.BOTTOM : Gravity.CENTER);
}
super.setPressed(pressed);
}
}
i'm trying to extend an HorizontalScrollView with a RadioGroup inside, when i populate the radiogroup all the button become selected on click, instead only the one i clicked
this is my class:
package widgets;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.widget.CompoundButton;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class HorizontalListView extends HorizontalScrollView {
ArrayList<String> lista = new ArrayList<String>();
ArrayList<RadioButton> listaButton = new ArrayList<RadioButton>();
int selected = -1;
Drawable itemSelector;
Context context;
android.widget.CompoundButton.OnCheckedChangeListener listener;
RadioGroup group;
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initView();
}
public HorizontalListView(Context context, ArrayList<String> stringhe, Drawable itemBackground) {
super(context);
this.context = context;
this.lista = stringhe;
this.itemSelector = itemBackground;
initView();
}
#SuppressLint("NewApi")
private synchronized void initView() {
this.removeAllViews();
group = new RadioGroup(getContext());
group.setOrientation(RadioGroup.HORIZONTAL);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
this.addView(group, params);
int i = 0;
for (String string : lista) {
RadioButton button = new RadioButton(getContext());
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
button.setBackgroundDrawable(itemSelector);
} else {
button.setBackground(itemSelector);
}
button.setButtonDrawable(new StateListDrawable());
button.setText(string);
button.setTag(i);
LayoutParams paramsButton = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
button.setPadding(20, 0, 20, 0);
listaButton.add(button);
group.addView(button, paramsButton);
i++;
}
}
and this is my selector, i made all the state i need to select the correct one, but as i said the radiogroup select all the items (they also become selected if i scroll the horizontalscrollview)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_pressed="false"><shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="#color/sinottica_button_border" />
<solid android:color="#color/sinottica_button_bg_selected" />
<padding android:bottom="2dp" android:left="5dp" android:right="5dp" android:top="2dp" />
</shape></item>
<item android:state_checked="false" android:state_pressed="false"><shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="#color/sinottica_button_border" />
<solid android:color="#color/sinottica_button_bg" />
<padding android:bottom="2dp" android:left="5dp" android:right="5dp" android:top="2dp" />
</shape></item>
<item android:state_checked="true" android:state_pressed="true"><shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="#color/sinottica_button_border" />
<solid android:color="#color/sinottica_button_bg_selected" />
<padding android:bottom="2dp" android:left="5dp" android:right="5dp" android:top="2dp" />
</shape></item>
<item android:state_checked="false" android:state_pressed="true"><shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="1dp" android:color="#color/sinottica_button_border" />
<solid android:color="#color/sinottica_button_bg" />
<padding android:bottom="2dp" android:left="5dp" android:right="5dp" android:top="2dp" />
</shape></item>
</selector>
UPDATE:
i tried to not remove the StateListDrawable, so i commented this row
button.setButtonDrawable(new StateListDrawable());
now i have the checkbox over my textview, but while the background is out of sync with the selection, (change when i scroll, the other radiobutton in the group change their selection state when i touch one button) the checkmark is correct... there is a way to put the statelist drawable as background for the Button instead of the default (on the left of the button)
MOCK UP
Requirement
I want to put custom button with selector.
Mock up is given above.
If anyone knows solution then share it.
Thank you.
basically you will need to create some new XML files and apply them to your Button element. As i can see from the mockup you will need a stroke and the background color with some shading effect applied, you can research more into the shading thing but the background color and the stroke is pretty straight forward.
Here is an example, done_rounded_btn.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="#drawable/zzzzzzzzz_btn_orange" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="#drawable/zzzzzzzzz_btn_orange" />
<item
android:state_focused="false"
android:state_enabled="false"
android:drawable="#drawable/zzzzzzzzz_btn_inactiv" />
<item android:drawable="#drawable/zzzzzzzzz_btn_black"/>
</selector>
for the selection part and then you create the custom drawables corresponding to the mockup.
An example, zzzzzzzzzz_btn_orange:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid
android:color="#color/done_color">
</solid>
<corners
android:bottomLeftRadius="3dp"
android:bottomRightRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp" />
</shape>
And then add it to your button as background, main.xml:
<Button
android:id="#+id/registers_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/done_rounded_btn"
android:text="#string/done_txt"
android:textColor="#color/white"
android:textSize="15sp" />
Hope this helps!
You can use this instead of standard Button and set selector as background in xml:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
/**
* Custom Shape Button which ignores touches on transparent background.
*/
public class ButtonWithUntouchableTransparentBg extends Button {
public ButtonWithUntouchableTransparentBg(Context context) {
this(context, null);
}
public ButtonWithUntouchableTransparentBg(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ButtonWithUntouchableTransparentBg(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDrawingCacheEnabled(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
// ignores touches on transparent background
if (isPixelTransparent(x, y))
return true;
else
return super.onTouchEvent(event);
}
/**
* #return true if pixel from (x,y) is transparent
*/
private boolean isPixelTransparent(int x, int y) {
Bitmap bmp = Bitmap.createBitmap(getDrawingCache());
int color = Color.TRANSPARENT;
try {
color = bmp.getPixel(x, y);
} catch (IllegalArgumentException e) {
// x or y exceed the bitmap's bounds.
// Reverts the View's internal state from a previously set "pressed" state.
setPressed(false);
}
// Ignores touches on transparent background.
if (color == Color.TRANSPARENT)
return true;
else
return false;
}
}
You can also create a shape that is using a selector inside. If your shape is just changing its color in different states, this is a lot cleaner.
color/color_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/blue_dark" android:state_pressed="true" />
<item android:color="#color/blue_light" />
</selector>
drawable/shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/color_selector" />
<corners android:bottomLeftRadius="6dip" android:bottomRightRadius="6dp" />
<padding android:bottom="0dip" android:left="0dip" android:right="0dip" android:top="0dip" />
</shape>
Button with rounded corners with two states (enabled/disabled):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/white" />
<stroke android:width="1dp" android:color="#color/orange" />
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="28dp" />
<solid android:color="#color/grey_card_background" />
<stroke android:width="1dp" android:color="#color/grey" />
</shape>
</item>
</selector>
inside your item put the shape in the selector XML
EX FROM MY CODE :
<!-- if pressed -->
<item android:state_pressed="true"><shape android:padding="10dp" android:shape="rectangle">
<solid android:color="#color/blue" />
<corners android:bottomLeftRadius="10dp" android:bottomRightRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp" />
</shape></item>
<!-- if not pressed -->
<item><shape android:padding="10dp" android:shape="rectangle">
<solid android:color="#color/Purbble" />
<corners android:bottomLeftRadius="10dp" android:bottomRightRadius="10dp" android:topLeftRadius="10dp" android:topRightRadius="10dp" />
</shape></item>