安卓点击事件button
java端代码
1 package com.example.test; 2 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.Menu; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.Toast; 9 10 public class MainActivity extends Activity { 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 //获得buttonID 17 Button button = (Button)findViewById(R.id.myBytton); 18 //监听Button 19 button.setOnClickListener(new Button.OnClickListener() 20 { 21 @Override 22 public void onClick(View v) { 23 //实现显示消息 24 DisplayToast("事件触发了"); 25 } 26 }); 27 } 28 @Override 29 public boolean onCreateOptionsMenu(Menu menu) { 30 // Inflate the menu; this adds items to the action bar if it is present. 31 getMenuInflater().inflate(R.menu.main, menu); 32 return true; 33 } 34 35 private void DisplayToast(String string) { 36 // TODO Auto-generated method stub 37 Toast.makeText(this, string, Toast.LENGTH_LONG).show(); 38 } 39 }
layout代码
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" > 10 11 <Button 12 android:id="@+id/myBytton" 13 android:layout_width="fill_parent" 14 android:layout_height="wrap_content" 15 android:text="点我" /> 16 </RelativeLayout>
以上的代码实现的是点击Button事件. 源码下载