按钮(Button)在很多应用程序中都很常见,应该是用户交互中使用最多的组件。当用户单击按钮的时候,会有一定的响应动作。
下面我们就来学一下这个按钮相关的内容。
1,放置Button按钮
对应的xml文件的内容是
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="@+id/textView1"
android:text="Button" />
这段代码的意思是,在用户界面上放置了一个
id 为“button1”的按钮,按钮的高度(layout_height)和宽度(layout_width)都会根据实际内容进行调整(wrap_content),按钮的名字也就是按钮上面的字为
Button,运行这段代码,其效果如图所示。
按钮的功能最重要的就是“单击”事件,下面为button添加监听,以感知到点击的操作。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) this.findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO Auto-generated method stub
setTitle("button1 被用户点击了");
Log.i("widgetDemo", "button1 被用户点击了。");
}
});
onCreate()方法中,通过findViewById(R.id.button1)获得button1的对象,通过setOnClickListener(new View.OnClickListener() 对button1设置监听,这样当button1被点击的时候,就能被感知到。
运行结果如图所示: