main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点我1"
/>
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="点我2"
/>
</LinearLayout>
strings.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">按钮的设置!</string>
<string name="app_name">ButtonDemo</string>
</resources>
MainActivity.java文件
package com.xuefei.button.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private Button btn1=null;
private Button btn2=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.btn1);
btn2=(Button)findViewById(R.id.btn2);
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
}
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
// btn1=(Button)findViewById(R.id.btn1);
// btn2=(Button)findViewById(R.id.btn2);
// btn1.setOnClickListener(new OnClickListener()
// {
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// Toast.makeText(MainActivity.this, "你点击了按钮1。",Toast.LENGTH_SHORT ).show();
//
// }
// });
// btn2.setOnClickListener(new OnClickListener()
// {
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// Toast.makeText(MainActivity.this, "你点击了按钮2。",Toast.LENGTH_SHORT ).show();
//
// }
// });
//
//class ButtonClick implements OnClickListener
//{
// public void onClick(View v)
// {
// System.out.println("你点击了按钮!");
// }
//}
//内部匿名类
private OnClickListener listener=new OnClickListener()
{
@Override
public void onClick(View v)
{
Button btn=(Button)v;
switch (btn.getId())
{
case R.id.btn1:
Toast.makeText(MainActivity.this, "你点击了按钮1。",Toast.LENGTH_SHORT ).show();
break;
case R.id.btn2:
Toast.makeText(MainActivity.this, "你点击了按钮2。",Toast.LENGTH_SHORT ).show();
break;
}
}
};
}