android--widget介绍之Button
Button是常用的控件,用起来也很简单。
有2种创建方法
1. 在界面xml描述文档中定义:
<RelativeLayout android:id=”@+id/buttonLayout”
android:orientation=”horizontal”
android:layout_width=”fill_parent”
android:layout_height=”45px”
ndroid: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>
2.在程序中创建
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);//加到界面中
优缺点比较:
在xml文档中定义,一旦界面要改变是话,直接修改一下xml就行了,不用修改Java程序,并且在xml中定义层次分明,一目了然。如果在程序中定义,还要将其加入到界面中,有的还要设置高度宽度,样式之类的,会使程序变得臃肿,开发和维护都不方便。
接下来是要给按钮加一个监听了,就是响应点击按钮的事件。
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(), “Hello world!”, Toast.LENGTH_LONG);//提示被点击了
toast.show();
}
});
按钮时一个常用控件,设置好样式,定义好点击触发响应就ok了。如果需要显示图片,则需要使用ImageButton了。