モックアップ
要件
カスタム ボタンをselectorに配置したい。
モックアップは上に与えられています。
誰かが解決策を知っている場合は、それを共有してください。
ありがとうございました。
内部でセレクターを使用している形状を作成することもできます。形状がさまざまな状態で色を変えているだけの場合、これはずっときれいです。
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>
標準のボタンの代わりにこれを使用して、セレクターを 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;
}
}