<Button
android:id="@+id/btn1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text = "Click"
/>
<Button
android:id="@+id/btn2"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text = "Click2"
/>
public class MainActivity extends Activity {
private Button btn1 = null;
private Button btn2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn1.setOnClickListener(listener);
btn2.setOnClickListener(listener);
}
private View.OnClickListener listener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Button btn = (Button)v;
switch(btn.getId())
{
case R.id.btn1:
Toast.makeText(MainActivity.this,"You Click the Button!",Toast.LENGTH_LONG).show();
break;
case R.id.btn2:
System.out.println("You Clicked Button 2");
break;
}
}
};
@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;
}
}
评论