我有一个快门按钮,它实现了它自己的侦听器来处理焦点和单击事件在这里,有两种方法,一种用于焦点,另一种用于单击。我发现这些方法没有被调用...
我的自定义视图扩展了 ImageView 如下:
public class ShutterButton extends ImageView {
public ShutterButton(Context context)
{
super(context);
}
public ShutterButton(Context context,AttributeSet attrs)
{
super(context,attrs);
}
public ShutterButton(Context context,AttributeSet attrs,int defStyle)
{
super(context,attrs,defStyle);
}
interface ShutterButtonListener
{
public void onShutterButtonFocus(ShutterButton shutterButton,boolean pressed);
public void onShutterButtonClick(ShutterButton shutterButton);
}
ShutterButtonListener mListener;
boolean mOldPressed;
boolean mTouchEnabled=true;
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
if(mTouchEnabled)
return super.dispatchTouchEvent(ev);
else
return false;
}
public void enableTouch(boolean enable)
{
mTouchEnabled=enable;
}
@Override
public void drawableStateChanged()
{
super.drawableStateChanged();
final boolean pressed=isPressed();
/*
* When pressing a physical camera button:
* pressed(true),optional click,pressed(false)
* Another option that we could use is:
* pressed(true),pressed(false),optional click...
* The second set of events occurs when the drawable state gets updated first.
* To emulate a physical camera button,push back pressed(false) in the event queue.
* */
if(pressed!=mOldPressed)//indicates state change
{
if(!pressed)//setting to false once shutter has been clicked(true->false)
{
post(new Runnable(){
@Override
public void run()
{
callShutterButtonFocus(pressed);
}
});
}
else//(false->true)clicking the shutter
callShutterButtonFocus(pressed);
}
mOldPressed=pressed;
}
private void callShutterButtonFocus(boolean pressed)
{
if(mListener!=null)
{
mListener.onShutterButtonFocus(this,pressed);
}
}
public void setShutterButtonListener(ShutterButtonListener listener)
{
mListener=listener;
}
@Override
public boolean performClick()
{
boolean result=super.performClick();
if(mListener!=null &&getVisibility()==View.VISIBLE)
{
mListener.onShutterButtonClick(this);
}
return result;
}
}
在使用此 ShutterButton 的 Activity 中:
btn_capture=(com.example.mycameraapp.ShutterButton)findViewById(R.id.btn_capture);
btn_capture.setShutterButtonListener(this);
btn_capture.setVisibility(View.VISIBLE);
@Override
public void onShutterButtonFocus(ShutterButton shutterButton,
boolean pressed) {
// TODO Auto-generated method stub
Log.d(TAG, "Shutter button focus called");
switch(shutterButton.getId())
{
case R.id.btn_capture:
doFocus(pressed);
break;
}
}
@Override
public void onShutterButtonClick(ShutterButton shutterButton) {
// TODO Auto-generated method stub
Log.d(TAG, "Shutter button click called");
switch(shutterButton.getId())
{
case R.id.btn_capture:
doSnap();
break;
}
}
这里的所有代码都取自: