在MainActivity中
public class MainActivity extends Activity implements OnClickListener{
TextView tv; Button bt1,bt2,bt3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); bt1=(Button) findViewById(R.id.bt1); bt2=(Button) findViewById(R.id.bt2); bt3=(Button) findViewById(R.id.bt3); //内部类实现 bt1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv.setText("我是按钮1"); } }); //主类继承 bt2.setOnClickListener(this); bt3.setOnClickListener(new MyOnclickListener()); } //1.自定义类 class MyOnclickListener implements OnClickListener {@Override
public void onClick(View v) { // TODO Auto-generated method stub tv.setText("我是按钮3"); } } //在布局文件中定义 public void onClick4(View v) { tv.setText("我是按钮4"); }
@Override
public void onClick(View v) { // TODO Auto-generated method stub tv.setText("我是按钮2"); }
布局文件xml中
<LinearLayout xmlns:android=""
xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"android:orientation="vertical"
tools:context=".MainActivity" ><TextView
android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="200dp" android:gravity="center" android:text="@string/hello_world" /><Button
android:id="@+id/bt1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/tv" android:text="按钮1" /><Button
android:id="@+id/bt2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/bt1" android:text="按钮2" /><Button
android:id="@+id/bt3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/bt2" android:text="按钮3" /><Button
android:onClick="onClick4" android:id="@+id/bt4" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/bt3" android:text="按钮4" /></RelativeLayout>