我们先在程序中定义一个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”>
接下来是要给按钮加一个监听了,就是响应点击按钮的事件。这个是在程序中完成了,
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(), “I am Clicked”, Toast.LENGTH_LONG);//提示被点击了
toast.show();
}
});
好了,按钮就是这么简单。