[英]Android - Custom Button gets stuck “Pressed”
我在Android應用程序中創建了一個自定義按鈕,該按鈕基本上具有兩個不同的視圖。 有一個圖像用於未按下按鈕,另一圖像用於按下按鈕。 以下是我實現按鈕的方式以及它對用戶的響應。
private void registerListeners() {
calcButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
calcButton.requestFocusFromTouch();
calcButton.setImageResource(R.drawable.calc_button_pressed);
return false;
}
});
calcButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
calcButton.setImageResource(R.drawable.calc_button_not_pressed);
}
});
calcButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mathCalculation();
calcButton.setImageResource(R.drawable.calc_button_not_pressed);
}
});
}
我的問題是存在一個“錯誤”,如果用戶觸摸該按鈕並將其圖形拖離該按鈕,該按鈕將保持按下狀態。 我上面實現的一種解決方法是“ setOnFocusChangeListener”,因此一旦用戶選擇了其他內容,它就會彈出。
我想要它,以便當用戶將按鈕拖到那里時,按鈕彈出來。
所有建議,不勝感激!!!
謝謝,
您無需編寫單獨的按鈕類即可獲得該行為,您可以通過可繪制的xml實現它。 在您的xml中保存此文件,並將其設置為按鈕的背景:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/calc_button_pressed" />
<item android:drawable="@drawable/calc_button_not_pressed" />
</selector>
在您的onTouch方法中,檢查事件操作。
calcButton.setImageResource(R.drawable.calc_button_not_pressed);
http://developer.android.com/reference/android/view/MotionEvent.html
您可以使用use onTouch
。 然后使用當用戶觸摸時將觸發的ACTION_OUTSIDE
移出視圖邊界。
編輯1:更具體:
OnTouchListener(MotionEvent e) {
switch(e.getAction()) {
case MotionEvent.ACTION_OUTSIDE: // switch the image if the button
}
}
這是因為單擊事件僅在觸摸和釋放時才“發生”。 如果您要觸摸並移到外面,那不是單擊。
要使用StateListDrawable完成您想要的操作 ,它就是為此而創建的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.