Android 给Button加个监听

在Android开发过程中,Button是常用的控件,用起来也很简单,你可以在界面xml描述文档中定义,也可以在程序中创建后加入到界面中,其效果都是一样的。不过最好是在xml文档中定义,因为一旦界面要改变是话,直接修改一下xml就行了,不用修改Java程序,并且在xml中定义层次分明,一目了然。另一个是如果在程序中定义,还要将其加入到界面中,有的还要设置高度宽度,样式之类的,会使程序变得臃肿,开发和维护都不方便。

我们先在程序中定义一个Button

Button button = new Button(this);//定义一个button,其中this是上下文,这段代码是在一个Activity的onCreate中创建的。

button.setWidth(100);//一定要设置宽和高。不然会出错的。

button.setHeight(50);

button.setText(“Click me”);//按钮上的文字

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.buttonLayout);

relativeLayout.addView(button);//加到界面中

以下是在UI xml中定义的按钮。

<RelativeLayout android:id=”@+id/buttonLayout”

android:orientation=”horizontal”

android:layout_width=”fill_parent”

android:layout_height=”45px”

android:background=”#ffffff”

android:layout_alignParentBottom=”true”>

<Button

android:id=”@+id/button”

android:text=” Click me”

android:layout_alignParentLeft=”true”

android:layout_alignParentBottom=”true”

android:layout_width=”100px”

android:layout_height=”50px”/>

</RelativeLayout>

接下来是要给按钮加一个监听了,就是响应点击按钮的事件。这个是在程序中完成了,

button.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

Toast toast = Toast.makeText(getApplicationContext(), “I am Clicked”, Toast.LENGTH_LONG);//提示被点击了

toast.show();

}

});

好了,按钮就是这么简单。

转载请标明出处:[url=http://blog.3gstdy.com/]3G Study[/url] :[url=http://blog.3gstdy.com/archives/4]http://blog.3gstdy.com/archives/4[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值