我有一个快门按钮,可以实现自己的侦听器,用于处理焦点和点击事件 这里有两种方法,一种用于焦点,另一种用于点击。我发现这些方法没有被调用......
我的自定义视图扩展了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;
}
}
此处的所有代码均取自:
答案 0 :(得分:1)
尝试在xml布局中制作clickable=true
或在代码中制作setClickalbe(true)
。
无论如何,使用performClick
并不是一个非常好的方法来使用android中的视图。