1.使用setOnClickListener方法监听按钮消息
package Button.bt;
import java.security.PublicKey;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ButtonActivity extends Activity {
private Button myButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button)findViewById(R.id.mButton);
myButton.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
}
});
}
2. 以内部类的形式构建按钮的监听器
package Button.bt;
import java.security.PublicKey;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonActivity extends Activity {
private Button myButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button)findViewById(R.id.mButton);
}
// 自定义myButton类,对按钮消息监听,内部类可以使用外部类的变量
class myButtonListener implements OnClickListener
{
public void onClick(View v)
{
// TODO Auto-generated method stub
}
}
}
3. 在xml布局文件中的代码如下:
<Button
android:id= "@+id/mButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="bt" //关键是这句
></Button>
java代码:
package Button.bt;
import java.security.PublicKey;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonActivity extends Activity {
private Button myButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button)findViewById(R.id.mButton);
}
public void bt(View myButton)
{
// TODO Auto-generated method stub
}
}
4.仔细观察后会发现,这种方法和第二种其实很相似。
package Button.bt;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class ButtonActivity extends Activity {
private Button myButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button)findViewById(R.id.mButton);
myButton.setOnClickListener (mListener);
}
Button.OnClickListener mListener = new Button.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
}
};
}
注:转载请注明出处http://blog.csdn.net/zjbpku