Android笔记:Button
示例代码摘自《第一行代码》
ButtonDemo.java的代码:
public class ButtonDemo extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_button);
Button button1 = (Button) findViewById(R.id.button_1); //加载按钮
button1.setOnClickListener(new OnClickListener() { //注册监听事件
@Override
public void onClick(View v) {
Toast.makeText(ButtonDemo.this, "You clicked Button 1",
Toast.LENGTH_SHORT).show(); //弹出消息
}
});
}
}
Layout的demo_button.xml:
<Button android:id="@+id/button_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button 1" />
效果如下所示: