首页 > 代码库 > android基础之点击监听器的2种监听实现
android基础之点击监听器的2种监听实现
点击监听器接口:onClickListener
抽象函数 onClick(View v)
有2个方法实现监听:
1:当前类继承点击监听器接口
package com.example.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private Button btn_ok,btn_cancel;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_ok=(Button)findViewById(R.id.btn_ok);
btn_cancel=(Button)findViewById(R.id.btn_cancel);
tv=(TextView)findViewById(R.id.tv);
btn_ok.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}
public void onClick(View v)
{
if(v==btn_ok)
{
tv.setText("确定按钮触发事件");
}else if(v==btn_cancel)
{
tv.setText("取消按钮触发事件");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
2:使用内部类实现点击监听器接口
package com.example.button;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity{
private Button btn_ok,btn_cancel;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_ok=(Button)findViewById(R.id.btn_ok);
btn_cancel=(Button)findViewById(R.id.btn_cancel);
tv=(TextView)findViewById(R.id.tv);
btn_ok.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
tv.setText("确定触发事件");
}
}
);
btn_cancel.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
tv.setText("取消按钮触发事件");
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
本文出自 “hagar” 博客,请务必保留此出处http://7832308.blog.51cto.com/7822308/1429158