Li Gang's Android crazy handout is really "crazy", wasting 3 days, whether his code is a problem, or how unclear.
Problem Description: In his book, section 3.3 is based on the callback event handling propagation routines. To disguise the example program based on the callback event propagation, the source code is as follows: Mybutton.java
public class MyButton extends Button
{
public MyButton(Context context , AttributeSet set)
{
super(context , set);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onKeyDown(keyCode , event);
Log.v("-MyButton-" , "the onKeyDown in MyButton");
//返回false,表明并未完全处理该事件,该事件依然向外扩散
return false;
}
}
Propagation.java
public class Propagation extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyButton bn = (MyButton)findViewById(R.id.bn);
//bn.setFocusable(true);
bn.requestFocus();
bn.setFocusableInTouchMode(true);
//为bn绑定事件监听器
bn.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View source
, int keyCode, KeyEvent event)
{
//只处理按下键的事件
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
Log.v("-Listener-" , "the onKeyDown in Listener");
}
// 返回false,表明该事件会向外传播
return false;
}
});
}
//重写onKeyDown方法,该方法可监听它所包含的所有组件的按键被按下事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onKeyDown(keyCode , event);
Log.v("-Activity-" , "the onKeyDown in Activity");
//返回false,表明并未完全处理该事件,该事件依然向外扩散
return false;
}
}
MyButton inherits the button and overrides the OnKeyDown method, which is important when the control has the focus and triggers the method when a key is pressed on the component ,Similar to onkeyup and onkeypress. Here comes a focus issue. So what is the focus problem: the focus can be understood as the object we are manipulating, the focus is here, and it can be manipulated. In fact, this mybutton is in the activity, and our programwhen running the focus on the activity, which caused the inside of the mybutton can not operate, I understand so, hehe. So the procedure to add two lines is:
Here is the reason for using requstfocuns instead of setfocusable is to set whether to allow this control to have the ability to gain focus, which is the request to get focus, and the other is to set the property, anotherone is to execute the action, so we use the latter, Setfocunsableintouchmode is the way to get the focus, we are the focus when touching. When set, focus positioningin theon this button, when you click on any key of the simulator, the program is logcat correct output. This procedure is intended to demonstrate that if any one of the event-handling methods returns True, the event also inherits outward propagation. I do not understand the book "first move the focus to the Program Interface button" is a few meaning, confused for a long time.
From for notes (Wiz)
Custom button, onkeydown inside the replication, does not work