您的位置:首页 > 移动开发 > Android开发

Android点击事件的4种写法

2014-12-13 14:53 369 查看
第一种:内部匿名类

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找按钮
Button bt_ok=(Button)findViewById(R.id.bt_ok);
//给按钮添加点击事件
bt_ok.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//查找TextView
TextView t_show=(TextView)findViewById(R.id.text_show);
//给TextView添加文字
t_show.setText("点击事件");
}
});
}


第二种:内部类

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找按钮
Button bt_ok=(Button)findViewById(R.id.bt_ok);
//给按钮添加点击事件
bt_ok.setOnClickListener(new MyListener());
}

private class MyListener implements OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//查找TextView
TextView t_show=(TextView)findViewById(R.id.text_show);
//给TextView添加文字
t_show.setText("点击事件");
}

}


第三种:MainActivity实现OnClickListener接口

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找按钮
Button bt_ok=(Button)findViewById(R.id.bt_ok);
//给按钮添加点击事件
bt_ok.setOnClickListener(this);
}

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//查找TextView
TextView t_show=(TextView)findViewById(R.id.text_show);
//给TextView添加文字
t_show.setText("点击事件");
}
}


第四种:布局文件添加函数

在布局文件button处添加

android:onClick="textshow"
然后在类MainActivity里添加textshow方法

public void textshow(View v){
//查找TextView
TextView t_show=(TextView)findViewById(R.id.text_show);
//给TextView添加文字
t_show.setText("点击事件");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: