注册事件

package net.learn2develop.UIActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity{
/**Calledwhentheactivityisfirstcreated.*/
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---the two buttons are wired to the same event handler---Button btn1 = (Button)findViewById(R.id.btn1);
btn1.setOnClickListener(btnListener);
Button btn2 = (Button)findViewById(R.id.btn2);
btn2.setOnClickListener(btnListener);
}
//---create an anonymous class to act as a button click listener---private OnClickListener btnListener= new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
((Button) v).getText() + “ was clicked”,
Toast.LENGTH_LONG).show();
}
};
@Override
public boolean onKeyDown(intkeyCode,KeyEventevent)
{
switch(keyCode)
{
//...
//...
}
returnfalse;
}
}
这是定义一个匿名类来注册事件。

import android.widget.EditText;
public class MainActivity extends Activity{
Listening for Ui notifications ❘ 121
/**Calledwhentheactivityisfirstcreated.*/
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---thetwobuttonsarewiredtothesameeventhandler---Buttonbtn1=(Button)findViewById(R.id.btn1);
btn1.setOnClickListener(btnListener);
Buttonbtn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(btnListener);

EditText txt1 = (EditText)findViewById(R.id.txt1);
//---create an anonymous inner class to act as an onfocus listener---txt1.setOnFocusChangeListener(newView.OnFocusChangeListener()
{
@Override
public void onFocusChange(View v, booleanhasFocus) {
Toast.makeText(getBaseContext(),
((EditText) v).getId() + “ has focus - “+ hasFocus,
Toast.LENGTH_LONG).show();
}
});
}
这是一个匿名内部类。

你可能感兴趣的:(android,类)