示例代码摘自《第一行代码》

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" />

效果如下所示:

Android笔记:Button

 

相关文章:

  • 2021-04-18
  • 2022-12-23
  • 2021-06-21
  • 2021-09-13
  • 2021-05-06
猜你喜欢
  • 2022-12-23
  • 2021-09-13
  • 2022-01-04
  • 2022-12-23
  • 2022-02-23
  • 2021-11-14
  • 2021-09-17
相关资源
相似解决方案