设为首页 加入收藏

TOP

Android 给Button加个监听
2014-11-24 03:00:56 来源: 作者: 【 】 浏览:2
Tags:Android Button 加个 监听

我们先在程序中定义一个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中定义的按钮。



android:orientation=”horizontal”


android:layout_width=”fill_parent”


android:layout_height=”45px”


android:background=”#ffffff”


android:layout_alignParentBottom=”true”>



android:id=”@+id/button”


android:text=” Click me”


android:layout_alignParentLeft=”true”


android:layout_alignParentBottom=”true”


android:layout_width=”100px”


android:layout_height=”50px”/>



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


button.setOnClickListener(new OnClickListener(){


public void onClick(View v) {


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


toast.show();


}


});


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android 中的ListView内容刷新问题 下一篇Android工程res文件下的三个drawa..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Announcing October (2025-12-24 15:18:16)
·MySQL有什么推荐的学 (2025-12-24 15:18:13)
·到底应该用MySQL还是 (2025-12-24 15:18:11)
·进入Linux世界大门的 (2025-12-24 14:51:47)
·Download Linux | Li (2025-12-24 14:51:44)