首先在xml文件中设置好布局,我这里就只设置三个按钮分别实现三种方法:下面是代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.cb.button.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/t1"
android:text="Button's 0" />

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="one"
android:id="@+id/b1"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="two"
android:id="@+id/b2"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="three"
android:id="@+id/b3"
/>
</LinearLayout>

 

之后是进行Activity文件的操作,重点在这里:

public class MainActivity extends AppCompatActivity {
private Button b1;
private Button b2;
private Button b3;
private TextView t1;
View.OnClickListener b11=new View.OnClickListener(){    //使用匿名类
@Override
public void onClick(View v) {
t1.setText("one");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.t1);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(b11);
b2=(Button)findViewById(R.id.b2);
b2.setOnClickListener(        //匿名内部类
new View.OnClickListener() {
@Override
public void onClick(View v) {
t1.setText("two");
}
}
);
b3=(Button)findViewById(R.id.b3);
b3.setOnClickListener(new Button3());    //类对象
}
class Button3 implements View.OnClickListener{    
@Override
public void onClick(View v) {
t1.setText("three");
}
}}

 

三种方法殊途同归,但熟悉更能理解这种监听机制。