【发布时间】:2018-09-19 07:30:02
【问题描述】:
我定义了以下按钮:
public class PressedButton extends Button {
private static final int[] STATE_PRESSED = {R.attr.state_pressed};
private static final int[] STATE_UNPRESSED = {R.attr.state_unpressed};
private boolean mIsPressed = false;
private boolean mIsUnpressed = false;
public PressedButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PressedButton(Context context) {
super(context);
}
public void setPressed(boolean isPressed) {mIsPressed = isPressed;}
public void setUnpressed(boolean isUnpressed) {mIsUnpressed = isUnpressed;}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 2);
if (mIsPressed) {
mergeDrawableStates(drawableState, STATE_PRESSED);
}
if (mIsUnpressed) {
mergeDrawableStates(drawableState, STATE_UNPRESSED);
}
return drawableState;
}
然后,在主 Activity 我这样称呼它:
PressedButton btn01=(PressedButton)findViewById(R.id.buttonP1);
当我尝试像这样设置 Click Listener 时:
btn01.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
typeLogin = 0;
Log.e("FINGERPRINT: ", "TypeLogin set to "+ new Integer(typeLogin).toString());
}
});
当我按下它时没有任何反应,按钮显示正确,但当我点击它时它没有输入代码,值得注意的是,当我使用 (Button) 而不是 (PressedButton) 时,它可以正常工作,所以我想知道我的自定义类做错了什么。
更多信息,我在这里使用选定的答案来创建一个带有状态的自定义按钮:How to add a custom button state,这是我的 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="buttonPressed">
<attr name="state_pressed" format="boolean" />
<attr name="state_unpressed" format="boolean" />
</declare-styleable>
</resources>
这是pressed_buton.xml
<?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/com.fgtit.fingermap">
<item
app:state_pressed="true"
app:state_unpressed="false"
android:drawable="@drawable/pressed" />
<item
app:state_pressed="false"
app:state_unpressed="true"
android:drawable="@drawable/unpressed" />
</selector>
最后,它在 MainActivity 中使用的按钮是这样的:
<com.fgtit.utils.PressedButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.fgtit.fingermap"
android:id="@+id/buttonP1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/msign"
android:height="100dp"
android:paddingTop="20dp"
android:text="@string/action_btn1"
android:textColor="@color/darkgreen"
android:width="180dp"
app:state_pressed="false"
app:state_unpressed="true"
android:background="@drawable/pressed"/>
【问题讨论】:
-
你试过实现
View.OnClickListener吗? -
我刚刚做了,但似乎没有任何区别,我什至尝试覆盖 OnClick 并放置一条日志消息,但它没有到达它
-
为什么注释掉覆盖装饰器?
-
@TheClansman 看看这个第一个和第二个答案。 stackoverflow.com/questions/8575959/…
标签: android button onclicklistener